C语言 使用'sprintf'将十六进制转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4770616/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting hex into a string using 'sprintf'
提问by Dberg
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!
}
回答by user411313
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
}
回答by leppie
Perhaps you need:
也许你需要:
&hex_tmp[i * 2]
And also a bigger array.
还有一个更大的阵列。
回答by Dberg
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', '##代码##' };
unsigned char arr2[] = { 70, 70, 0 };

