Logo

Programming-Idioms

  • Ada
  • Groovy

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

def s = a.encodeHex().toString()

encodeHex() returns a Writable, call toString() to convert it to a String.
#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...