Logo

Programming-Idioms

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

Idiom #175 Bytes to hex string

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

import "fmt"
s := fmt.Sprintf("%x", a)
import "encoding/hex"
s := hex.EncodeToString(a)
Int32 s = BitConverter.ToInt32(sampleBuffer, 0);
s = s.Replace("-", string.Empty);
using System;
var s = Convert.ToHexString(a);
import std.digest;
s = a.toHexString;
import 'dart:typed_data';
var s = a.buffer
    .asUint8List()
    .map((e) => e.toRadixString(16).padLeft(2, '0'))
    .join();
hexChar(Num) when Num < 10 andalso Num >= 0->
    $0 + Num;
hexChar(Num) when Num < 16 ->
    $a + Num - 10.

toHex([Byte | Rest]) ->
    [hexChar(Byte div 16), hexChar(Byte rem 16)] ++ toHex(Rest);
toHex([]) -> [].
  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
def s = a.encodeHex().toString()
const s = Buffer.from(a).toString('hex')
const s = a.map(n => n.toString(16).padStart(2, '0')).join('')
import java.util.HexFormat;
var s = HexFormat.of().formatHex(a);
import static java.lang.System.out;
import java.util.Formatter
StringBuilder S = new StringBuilder();
Formatter f = new Formatter(S);
for (byte b : a) f.format("%02x", b & 0xf);
f.flush();
String s = S.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)))))
for i,v in ipairs(a) do
 a[i]=string.format("%02x",v)
end
local s=table.concat(a)
uses 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*")
s = a.pack("c*").unpack("H*").first
use data_encoding::HEXLOWER;
let s = HEXLOWER.encode(&a);
fn byte_to_hex(byte: u8) -> (u8, u8) {
    static HEX_LUT: [u8; 16] = [b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7', b'8', b'9', b'a', b'b', b'c', b'd', b'e', b'f'];

    let upper = HEX_LUT[(byte >> 4) as usize];
    let lower = HEX_LUT[(byte & 0xF) as usize];
    (lower, upper)
}

let utf8_bytes: Vec<u8> = a.iter().copied().flat_map(|byte| {
        let (lower, upper) = byte_to_hex(byte);
        [upper, lower]
    }).collect();
let s = unsafe { String::from_utf8_unchecked(utf8_bytes) };
use core::fmt::Write;
let mut s = String::with_capacity(2 * n);
for byte in a {
    write!(s, "{:02X}", byte)?;
}
use hex::ToHex;
let s = a.encode_hex::<String>();

New implementation...