Logo

Programming-Idioms

  • C#
  • Java
  • C

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).

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;
byte[] a = new byte[s.Length/2];
for (int i = 0, h = 0; h < s.Length; i++, h += 2)
{
  a[i] = (byte) Int32.Parse(s.Substring(h, 2), System.Globalization.NumberStyles.HexNumber);
}
import static java.util.HexFormat.fromHexDigits;
int i, n = s.length();
byte a[] = new byte[n / 2];
for (i = 0; i < n; i = i + 2)
    a[i / 2] = (byte) fromHexDigits(s, i, i + 2);
public static byte[] hexToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                    + Character.digit(s.charAt(i+1), 16));
        }
        return data;
    }
import java.math.BigInteger;
byte[] a = new BigInteger(s, 16).toByteArray();
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.

New implementation...