On Tuesday, 6 February 2018 at 18:33:02 UTC, 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.

After a bunch of searching, I came across hex string literals. They are mentioned but not documented as a literal.
https://dlang.org/spec/lex.html#string_literals

Combined with the toHexString function in std.digest, it is easy to convert between hex strings and byte arrays.

import std.stdio;
import std.digest;

void main() {
    auto data = cast(ubyte[]) x"deadbeef";
    writeln("data: 0x", toHexString(data));
}

p.s. the cast should probably be to immutable ubyte[]. I'm guessing without it, there is an automatic copy of the data being made.

Reply via email to