On 02/06/2018 07:33 PM, Ralph Doncaster wrote:
I've been reading std.conv and std.range, trying to figure out a high-level way of converting a hex string to bytes.  The only way I've been able to do it is through pointer access:

import std.stdio;
import std.string;
import std.conv;

void main()
{
     immutable char* hex = "deadbeef".toStringz;
     for (auto i=0; hex[i]; i += 2)
         writeln(to!byte(hex[i]));
}


While it works, I'm wondering if there is a more object-oriented way of doing it in D.

I don't think that works as you intend. Your code is taking the numeric value of every other character.

But you want 0xDE, 0xAD, 0xBE, 0xEF, no? Here's one way to do that, but I don't think it qualifies as object oriented (but I'm also not sure how an object oriented solution is supposed to look):

----
void main()
{
    import std.algorithm: map;
    import std.conv: to;
    import std.range: chunks;
    import std.stdio;
    foreach (b; "deadbeef".chunks(2).map!(chars => chars.to!ubyte(16)))
    {
        writefln("%2X", b);
    }
}
----

Reply via email to