我一直在尝试将十进制从 1 到 99 转换为十六进制并将它们存储到数组中。
我拥有的是这样的东西:
int main(){
int i =1;
char dump_holder[3];
char hex_holder[100];
for (i=1;i<100;i++){
sprintf(dump_holder, "%02x",i);
hex_holder[i] = atoi(dump_holder);
printf("this: %02xn", hex_holder[i]);
}
return 0;}
我得到了某个数字的正确值。此代码返回:
this: 01
this: 02
this: 03
this: 04
this: 05
this: 06
this: 07
this: 08
this: 09
this: 00
this: 00
this: 00
this: 00
this: 00
this: 00
this: 0a
this: 0b
this: 0c
this: 0d
this: 0e
this: 0f
this: 10
this: 11
this: 12
this: 13
this: 01
this: 01
this: 01
this: 01
this: 01
this: 01
this: 14
this: 15
this: 16
this: 17
this: 18
this: 19
this: 1a
this: 1b
this: 1c
this: 1d
我认为杂散值是空终止符,但我不确定。
好吧,基本的事情是我无法理解您实际上想要实现的目标
但我会尽力而为:
int main(){
int i =1;
char dump_holder[3];
char hex_holder[100];
for (i=1;i<100;i++){
/* convert numerical value to string */
sprintf(dump_holder, "%02x",i);
/* convert string value back to numerical value */
//hex_holder[i] = atoi(dump_holder); //won't work
hex_holder[i] = strtol(dump_holder, NULL, 16); // this will
/* print the numerical value in hex representation */
printf("this: %02xn", hex_holder[i]);
}
return 0;}
- 您是否正在尝试以十六进制格式创建值的字符串表示形式? 如果是这样,那么您就以错误的方式执行此操作
- 现在你除了浪费进程电源之外什么也没做
即便如此,我还是添加了一个小代码,该代码实际上会将代码转换为值的字符串表示形式。也许这就是你真正打算做的
int main()
{
int i = 1;
char dump_holder[3];
/* the array should be an array of strings (restricted here to 2chars) */
char hex_holder[100][2];
for (i=1;i<100;i++){
/* convert numerical value to string representation */
sprintf(hex_holder[i], "%02x",i);
/* print the string produced */
printf("this: %sn", hex_holder[i]);
}
return 0;
}
atoi
采用十进制表示形式,请尝试strtol(dump_holder, NULL, 16);
。
要理解代码中的问题,首先需要了解 -atoi
如何工作?
阅读有关atoi
的信息并浏览演示其行为的示例 这里。
在你的程序输出中,09
后你会得到六倍的00
,因为atoi
返回十六进制值0a
、0b
、0c
、0d
、0e
和0f
的0
。
在此之后,程序输出为:this: 0a
this: 0b
this: 0c
this: 0d
this: 0e
this: 0f
原因是 -0f
之后的十六进制值是10
。10
存储在传递给atoi
dump_holder
变量中。atoi
返回的整数值10
存储在hex_holder[i]
中。
程序正在使用格式说明符打印存储在hex_holder[i]
中的值,该值的类型为char
%x
。因此,10
的值被打印为0a
。
使用不正确的格式说明符是未定义的行为,其中包括它可能完全按照程序员的意图执行或静默生成不正确的结果或其他任何内容。
只需将十进制从 1 到 99 转换为十六进制并将它们存储到数组中,您可以执行以下操作:
#include <stdio.h>
int main() {
char hex_holder[100][3];
for (int i = 1; i < 100; i++) {
snprintf (hex_holder[i], 3, "%02x", i);
printf("this: %sn", hex_holder[i]);
}
return 0;
}