gpt4 book ai didi

从十六进制转换为 2 的补码

转载 作者:太空宇宙 更新时间:2023-11-04 08:01:29 26 4
gpt4 key购买 nike

我试图将给定的十六进制转换为 2 的补码,但我的程序中出现了一些奇怪的情况。 (赋值是取两个给定的八进制、二进制、十六进制或十进制的数字,对它们进行加法/减法,然后转换为给定的基数)

我使用命令:./a.out + x1111 x1111 x

#include <stdio.h>

int main (int argc, char* arg[]){
int num1=0, num2=0, converted = 0;
if ((argc < 5) || (argc > 5))
{
printf("ERROR: please enter input in the following format\n");
printf("/calc <operation> <number1> <number2> <output base>\n");
}
else{
if (arg[2][0] == 'x'){
num1 = HexAsciiTo2comp(arg[2]);
printf("%d\n", num1);
}
if (arg[3][0] == 'x'){
num2 = HexAsciiTo2comp(arg[3]);
printf("%d\n", num2);
}
}
converted = num1 + num2;
finalOutput(converted, arg[4]);
return 0;
}

int HexAsciiTo2comp(char* hexNum){
int value = 0, i = 1;
printf("The original Hex Value is %s\n", hexNum);
for(i=1; i<9; i++){
switch(hexNum[i]){
case '0': value = value << 4; break;
case '1': value = (value << 4)+1; break;
case '2': value = (value << 4)+2; break;
case '3': value = (value << 4)+3; break;
case '4': value = (value << 4)+4; break;
case '5': value = (value << 4)+5; break;
case '6': value = (value << 4)+6; break;
case '7': value = (value << 4)+7; break;
case '8': value = (value << 4)+8; break;
case '9': value = (value << 4)+9; break;
case 'A': value = (value << 4)+10; break;
case 'B': value = (value << 4)+11; break;
case 'C': value = (value << 4)+12; break;
case 'D': value = (value << 4)+13; break;
case 'E': value = (value << 4)+14; break;
case 'F': value = (value << 4)+15; break;
default:break;
}
}return value;
}

结果是:

The original Hex Value is x1111
1118481
The original Hex Value is x1111
4369

4369 的后一个结果是正确的,但第一个输出不是。为什么会发生这种情况?

最佳答案

for循环运行只要i < 9是真的,但您的输入字符串较小。这意味着您还必须检查字符串结尾 ( i < 9 && hexNum[i] != '\0' ),否则您将访问字符串之外的数据。

关于从十六进制转换为 2 的补码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46396866/

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