Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting hex into a string using 'sprintf'

Tags:

c

I am trying to convert an array into hex and then put it into a string variable. In the following loop the printf works fine, but I can not use sprintf properly. How can I stuff the hex values into 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!
}
like image 799
Dberg Avatar asked Jan 22 '11 21:01

Dberg


1 Answers

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
}
like image 124
user411313 Avatar answered Nov 15 '22 06:11

user411313