Logo

Programming-Idioms

  • C++

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

String s = "";
for (byte b : a)
    s = s + "%02x".formatted(b);
import static java.util.stream.IntStream.range;
String s = range(0, n)
    .mapToObj(x -> a[x])
    .map("%02x"::formatted)
    .reduce(String::concat)
    .get();
import java.util.HexFormat;
var s = HexFormat.of().formatHex(a);

Since Java 17
#include <stdio.h>
#include <stdlib.h>
char *s = calloc(n * 2 + 1, 1);
for(int i = 0; i < n; ++i){
  char temp[3];
  sprintf(temp, "%02x", a[i]);
  s[2 * i] = temp[0];
  s[2 * i + 1] = temp[1];
}

New implementation...