移位在最高位给出 1

Shifting gives a 1 at the most significant digit

我目前正在编写一个 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] = '[=10=]';
}

代码大部分工作正常,除了当我输入奇数(例如:17)时,我在最重要的位置得到一个:

num = 17    binary = 100000000000000000000000000010001

偶数前的“1”不出现:

num = 16    binary = 000000000000000000000000000010000

我 运行 在一台远程 32 位 linux 机器上,这可能是原因吗?

您应该首先将 int 转换为 unsigned int,这将强制为 MSB 填充 0。

像这样:

unsigned int shift = (unsigned int)num >> i;

您正在创建一个 33 位二进制字符串,而不是 32 位:

for(int i = 0; i < 33; i++) {
    int shift = num >> i; //shift the current bit value of remainder i bits

假设 int 是 32 位宽,在循环的最后一次迭代中,您移动的量与您要移动的变量的大小相同。这样做会调用 undefined behavior. This is documented in section 6.5.7p3 of the C standard 关于移位运算符:

The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand. If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.

将循环的停止点改为32,并相应地调整减法和空终止字节的设置。

void Convert_Number_To_Binary(const int num,char *binary) {
    //Start from binary[0] and check if num is divisible by 2^ith power by shifting
    for(int i = 0; i < 32; 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] = '1';
        }
        else
                binary[32-i-1] = '0';
        //printf("i:%d, 32-i-1:%d\n", i, (32-i-1));
    }

    //printf("%c, %c", binary[0], binary[31]);

    binary[32] = '[=11=]';
}