Dberg
Dberg

Reputation: 245

Converting hex into a string using 'sprintf'

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!
}

Upvotes: 5

Views: 48021

Answers (3)

user411313
user411313

Reputation: 3990

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
}

Upvotes: 14

user295190
user295190

Reputation:

A char stored as numeric is not the same as a string:

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

Upvotes: -2

leppie
leppie

Reputation: 117220

Perhaps you need:

&hex_tmp[i * 2]

And also a bigger array.

Upvotes: 11

Related Questions