Programming-Idioms

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

Idiom #175 Bytes to hex string

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

string s = BitConverter.ToString(a);
import std.digest;
s = a.toHexString;
  use iso_c_binding, only : c_int8_t
  character(len=:), allocatable :: s
  allocate (character(len=2*size(a)) :: s)
  write(unit=s,fmt='(*(Z2.2))') a
import "encoding/hex"
s := hex.EncodeToString(a)
def s = a.encodeHex().toString()
(lambda (bytes &aux (size (* 2 (length bytes))))
  (let ((hex (make-array size :element-type 'character :fill-pointer 0)))
    (prog1 hex
      (with-output-to-string (o hex)
        (map () (lambda (byte) (format o "~2,'0x" byte)) bytes)))))
sysutils
s := '';
for b in a do s := s + IntToHex(b,2);
$s = unpack('H*', pack('c*', @a));
s = a.hex()
s = a.unpack("H*")
use core::fmt::Write;
let mut s = String::with_capacity(2 * n);
for byte in a {
    write!(s, "{:02X}", byte)?;
}
use hex::ToHex;
let mut s = String::with_capacity(2 * a.len());
a.write_hex(&mut s).expect("Failed to write");

Do you know the best way to do this in your language ?
New implementation...

Idiom created by

programming-idioms.org

Related idioms