Logo

Programming-Idioms

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

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

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([]) -> [].
#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...