gpt4 book ai didi

将十进制转换为十六进制并存储到 C 中的数组

转载 作者:行者123 更新时间:2023-11-30 19:06:16 25 4
gpt4 key购买 nike

我一直在尝试将十进制从 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: %02x\n", 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: %02x\n", 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: %s\n", hex_holder[i]);
}
return 0;
}

关于将十进制转换为十六进制并存储到 C 中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48422785/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com