Regarding hex strings
monarch_dodra
monarchdodra at gmail.com
Thu Oct 18 04:26:09 PDT 2012
On Thursday, 18 October 2012 at 11:24:04 UTC, monarch_dodra wrote:
> hex! was a very good idea actually, imo. I'll post my current
> impl in the next post.
>
//----
import std.stdio;
import std.conv;
import std.ascii;
template hex(string s)
{
enum hex = decode(s);
}
template hex(ulong ul)
{
enum hex = decode(ul);
}
ubyte[] decode(string s)
{
ubyte[] ret;
size_t p;
while(p < s.length)
{
while( s[p] == ' ' || s[p] == '_' )
{
++p;
if (p == s.length) assert(0, text("Premature end of
string at index ", p, "."));;
}
char c1 = s[p];
if (!std.ascii.isHexDigit(c1)) assert(0, text("Unexpected
character ", c1, " at index ", p, "."));
c1 = cast(char)std.ascii.toUpper(c1);
++p;
if (p == s.length) assert(0, text("Premature end of
string after ", c1, "."));
char c2 = s[p];
if (!std.ascii.isHexDigit(c2)) assert(0, text("Unexpected
character ", c2, " at index ", p, "."));
c2 = cast(char)std.ascii.toUpper(c2);
++p;
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;
}
ubyte[] decode(ulong ul)
{
//NOTE: This is not efficinet AT ALL (push front)
//but it is ctfe, so we can live it for now ^^
//I'll optimize it if I try to push it
ubyte[] ret;
while(ul)
{
ubyte t = ul%256;
ret = t ~ ret;
ul /= 256;
}
return ret;
}
//----
NOT a final version.
More information about the Digitalmars-d
mailing list