Convert hex to string using 'sprintf'

I am trying to convert an array to hex, and then put it in a string variable. In the next loop, printf works fine, but I can't use sprintf correctly. How can I fill in the hexadecimal values ​​in the array as ASCII?

static unsigned char  digest[16];
static unsigned char hex_tmp[16];

for (i = 0; i < 16; i++) {
  printf("%02x",digest[i]);  <--- WORKS
  sprintf(&hex_tmp[i], "%02x", digest[i]);  <--- DOES NOT WORK!
}
+3
source share
3 answers

Perhaps you need:

&hex_tmp[i * 2]

And an even larger array.

+9
source
static unsigned char  digest[16];
static char hex_tmp[33];

for (i = 0; i < 16; i++)  {
  printf("%02x",digest[i]);  <--- WORKS
  sprintf(&hex_tmp[i*2],"%02x", digest[i]);  <--- WORKS NOW
}
+9
source

A char stored as numeric does not match the string:

unsigned char i = 255;
unsigned char* str = "FF";
unsigned char arr1[] = { 'F', 'F', '\0' };
unsigned char arr2[] = { 70, 70, 0 };
-2
source

Source: https://habr.com/ru/post/1787197/


All Articles