Regarding hex strings

monarch_dodra monarchdodra at gmail.com
Thu Oct 18 05:57:17 PDT 2012


On Thursday, 18 October 2012 at 11:26:13 UTC, monarch_dodra wrote:
>
> NOT a final version.

With correct-er utf string support. In theory, non-ascii 
characters are illegal, but it makes for safer code, and better 
diagnosis.

//----
ubyte[] decode(string s)
{
     ubyte[] ret;;
     while(s.length)
     {
         while( s.front == ' ' || s.front == '_' )
         {
             s.popFront();
             if (!s.length) assert(0, text("Premature end of 
string."));;
         }

         dchar c1 = s.front;
         if (!std.ascii.isHexDigit(c1)) assert(0, text("Unexpected 
character ", c1, "."));
         c1 = std.ascii.toUpper(c1);

         s.popFront();
         if (!s.length) assert(0, text("Premature end of string 
after ", c1, "."));

         dchar c2 = s.front;
         if (!std.ascii.isHexDigit(c2)) assert(0, text("Unexpected 
character ", c2, " after ", c1, "."));
         c2 = std.ascii.toUpper(c2);
         s.popFront();

         ubyte val;
         if('0' <= c2 && c2 <= '9') val += (c2 - '0');
         if('A' <= c2 && c2 <= 'F') val += (c2 - 'A' + 10);
         if('0' <= c1 && c1 <= '9') val += ((c1 - '0')*16);
         if('A' <= c1 && c1 <= 'F') val += ((c1 - 'A' + 10)*16);
         ret ~= val;
     }
     return ret;
}
//----


More information about the Digitalmars-d mailing list