Logo

Programming-Idioms

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

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

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

Compute resulting hex string size, write to it as a string with format function
#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...