Logo

Programming-Idioms

  • JS
  • Go
  • D

Idiom #176 Hex string to byte array

From hex string s of 2n digits, build the equivalent array a of n bytes.
Each pair of hexadecimal characters (16 possible values per digit) is decoded into one byte (256 possible values).

import std.conv;
import std.string;
ubyte[] a = cast(ubyte[]) hexString!s.representation;

hexString can be used if s is known at compile time.
import std.algorithms;
import std.array;
import std.conv;
import std.range;
ubyte[] a = s.chunks(2)
             .map!(digits => digits.to!ubyte)
             .array;

Take 2 digits at a time and convert them to ubytes. Map is lazy so we use array to actually build a list.
s
  .split('')
  .map((el, ix, arr) => ix % 2 ? null : el + arr[ix + 1])
  .filter(el => el !== null)
  .map(x => parseInt(x, 16))

- split the string into an array
- transform into alternating pairs of two chars and null (you could do this more cleanly with a for loop)
- filter out the nulls
- parse the two-char strings (you could do this inside the first map but this way reads better)
import "encoding/hex"
a, err := hex.DecodeString(s)
if err != nil {
	log.Fatal(err)
}
const char* hexstring = "deadbeef";
size_t length = sizeof(hexstring);
unsigned char bytearray[length / 2];

for (size_t i = 0, j = 0; i < (length / 2); i++, j += 2)
	bytearray[i] = (hexstring[j] % 32 + 9) % 25 * 16 + (hexstring[j+1] % 32 + 9) % 25;

New implementation...