Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

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

$a = array_map('hexdec', str_split($s, 2));
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 std.algorithms;
import std.array;
import std.conv;
import std.range;
ubyte[] a = s.chunks(2)
             .map!(digits => digits.to!ubyte)
             .array;
import std.conv;
import std.string;
ubyte[] a = cast(ubyte[]) hexString!s.representation;
import 'package:convert/convert.dart';
var a = hex.decode(s);
  use iso_c_binding, only : c_int8_t
  integer(kind=c_int8_t), dimension(:), allocatable :: a

  allocate (a(len(s)/2))
  read(unit=s,fmt='(*(Z2))') a
import "encoding/hex"
a, err := hex.DecodeString(s)
if err != nil {
	log.Fatal(err)
}
s
  .split('')
  .map((el, ix, arr) => ix % 2 ? null : el + arr[ix + 1])
  .filter(el => el !== null)
  .map(x => parseInt(x, 16))
import java.math.BigInteger;
byte[] a = new BigInteger(s, 16).toByteArray();
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;
    }
uses sysutils;
for i := 0 to length(s) div 2 - 1 do
  a[i] := StrToInt('$'+Copy(s,2*(i)+1,2));
my @a = split '', pack 'H*', $s;
a = bytearray.fromhex(s)
a = [s].pack("H*").unpack("C*")
use hex::FromHex;
let a: Vec<u8> = Vec::from_hex(s).expect("Invalid Hex String");
use hex::decode;
let a: Vec<u8> = decode(s).expect("Hex string should be valid");
use data_encoding::HEXLOWER_PERMISSIVE;
let a: Vec<u8> = HEXLOWER_PERMISSIVE.decode(&s.into_bytes()).unwrap();

New implementation...