Logo

Programming-Idioms

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

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 'dart:typed_data';
var s = a.buffer
    .asUint8List()
    .map((e) => e.toRadixString(16).padLeft(2, '0'))
    .join();
#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...