fromHexString

Converts a hex text string to a range of bytes.

@safe pure
ubyte[]
fromHexString
(
String
)
(
String hex
)
if ()

Parameters

hex String

String representation of a hexdecimal-encoded byte array.

Return Value

Type: ubyte[]

An newly allocated array of bytes.

Throws

Exception on invalid input.

Examples

ubyte[] dby  = "0xBA".fromHexString;
// Single byte
assert("0xff".fromHexString  == [255]);
assert("0xff"w.fromHexString == [255]);
assert("0xff"d.fromHexString == [255]);
assert("0xC0".fromHexString  == [192]);
assert("0x00".fromHexString  == [0]);

// Nothing
assert("".fromHexString  == []);
assert(""w.fromHexString == []);
assert(""d.fromHexString == []);

// Nothing but a prefix
assert("0x".fromHexString  == []);
assert("0x"w.fromHexString == []);
assert("0x"d.fromHexString == []);

// Half a byte
assert("0x1".fromHexString  == [0x01]);
assert("0x1"w.fromHexString == [0x01]);
assert("0x1"d.fromHexString == [0x01]);

// Mixed case is fine.
assert("0xAf".fromHexString == [0xAF]);
assert("0xaF".fromHexString == [0xAF]);

// Multiple bytes
assert("0xfff".fromHexString     == [0x0F, 0xFF]);
assert("0x123AaAa".fromHexString == [0x01, 0x23, 0xAA, 0xAA]);
assert("EBBBBF".fromHexString    == [0xEB, 0xBB, 0xBF]);

// md5 sum
assert("d41d8cd98f00b204e9800998ecf8427e".fromHexString == [
    0xD4, 0x1D, 0x8C, 0xD9, 0x8F, 0x00, 0xB2, 0x04,
    0xE9, 0x80, 0x09, 0x98, 0xEC, 0xF8, 0x42, 0x7E,
]);
// Cycle self-test
const ubyte[] initial = [0x00, 0x12, 0x34, 0xEB];
assert(initial == initial.toHexString().fromHexString());

See Also

std.digest.fromHexString for a range version of the function.

Meta