我目前正在编写一个 C 函数,该函数从用户那里获取一个数字并将其转换为二进制输出。首先,这是代码:
void Convert_Number_To_Binary(const int num,char *binary) {
double remainder = num;
//Start from binary[0] and check if num is divisible by 2^ith power by shifting
for(int i = 0; i < 33; i++) {
int shift = num >> i; //shift the current bit value of remainder i bits
printf("i: %d, %d \n", i, (shift) );
//If shift is greater than 0, then remainder is divisible by 2^i
if( (shift & 1) > 0) {
binary[32-i] = '1';
}
else
binary[32-i] = '0';
//printf("i:%d, 32-i:%d\n", i, (32-i));
}
//printf("%c, %c", binary[0], binary[31]);
binary[33] = '\0';
}
该代码在大多数情况下都可以正常工作,除了当我输入一个奇数(例如:17)时,我在最重要的位置得到一个:
num = 17 binary = 100000000000000000000000000010001
偶数不出现前导“1”:
num = 16 binary = 000000000000000000000000000010000
我在远程 32 位 linux 机器上运行它,这可能是原因吗?