string to hex convert

Ali Çehreli acehreli at yahoo.com
Thu Mar 29 21:53:21 UTC 2018


On 03/29/2018 02:23 PM, Cym13 wrote:
> On Thursday, 29 March 2018 at 20:29:39 UTC, aerto wrote:
>> how i can convert Hello world! to hex 48656c6c6f20776f726c6421 ??
> 
> Maybe something like:
> 
> void main() {
>      // Those look like lots of imports but most of those are very 
> common anyway
>      import std.digest: toHexString;
>      import std.stdio: writeln;
> 
> 
>      string s = "Hello world!";
>      (cast(ubyte[]) s)    // We want raw bytes...
>          .toHexString     // ...convert them to hex...
>          .writeln;        // ...and print.
> }

For fun, here's a lazy version that uses a table. Apparently, 
toHexString does not use a table. I'm not measuring which one is faster. 
:) (Note: toHexString allocates memory, so it wouldn't be a fair 
comparison anyway.)

string asHex(char i) {
     import std.string : format;
     import std.algorithm : map;
     import std.range : iota, array;

     enum length = char.max + 1;
     static const char[2][length] hexRepresentation =
            iota(length).map!(i => format("%02x", i)).array;

     return hexRepresentation[i];
}

unittest {
     assert(0.asHex == "00");
     assert(128.asHex == "80");
     assert(255.asHex == "ff");
}

auto asHex(string s) {
     import std.string : representation;
     import std.algorithm : map, joiner;

     return s.representation.map!asHex.joiner;
}

unittest {
     import std.algorithm : equal;
     assert("Hello wörld!".asHex.equal("48656c6c6f2077c3b6726c6421"));
}

void main() {
}

Ali


More information about the Digitalmars-d-learn mailing list