使用“sprintf”将十六进制转换为字符串

时间:2021-06-22 15:44:59

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?

我试着把一个数组转换成十六进制,然后把它放到一个字符串变量中。在下面的循环中,printf运行良好,但是我不能正确地使用sprintf。如何将十六进制值以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 个解决方案

#1


10  

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
}

#2


9  

Perhaps you need:

也许你需要:

&hex_tmp[i * 2]

And also a bigger array.

还有一个更大的数组。

#3


-2  

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

#1


10  

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
}

#2


9  

Perhaps you need:

也许你需要:

&hex_tmp[i * 2]

And also a bigger array.

还有一个更大的数组。

#3


-2  

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