string to character code hex string

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Sep 2 09:52:17 PDT 2017


On 09/02/2017 09:23 AM, bitwise wrote:
> On Saturday, 2 September 2017 at 15:53:25 UTC, bitwise wrote:
>> [...]
>
> This seems to work well enough.
>
> string toAsciiHex(string str)
> {
>     import std.array : appender;
>
>     auto ret = appender!string(null);
>     ret.reserve(str.length * 2);
>     foreach(c; str) ret.put(format!"%x"(c));
>     return ret.data;
> }
>

Lazy version, which the user can easily generate a string from by 
appending .array:

import std.stdio;

auto hexString(R)(R input) {
     import std.conv : text;
     import std.string : format;
     import std.algorithm : map, joiner;
     return input.map!(c => format("%02x", c)).joiner;
}

void main() {
     writeln("AAA".hexString);
}

To generate string:

     import std.range : array;
     writeln("AAA".hexString.array);

Ali



More information about the Digitalmars-d-learn mailing list