0
我試圖將給定的十六進制轉換爲2的補碼數,但在我的程序中出現了一些奇怪的問題。 (分配給兩個給定的數字,可以是八進制,二進制,十六進制或十進制,加/減,然後轉換爲給定的基數)從十六進制轉換爲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後者結果是正確的但是所述第一輸出是沒有的。 爲什麼會發生這種情況?