首页 > 解决方案 > How is this function printing an integer in binary form?

问题描述

void DecInBinary(unsigned int dec) {                                   
int i = 0;
unsigned int highestOne = 1 << (sizeof(unsigned int)*8 - 1);
for (i = 0; i < sizeof(int)*8; i++)
    printf("%d", (dec & (highestOne >> i))>> (highestOne - i - 1));
}

In particular, I don't understand how the second right shift operator in the print statement results in either a '1' or '0'.

标签: c

解决方案


这个函数如何以二进制形式打印一个整数?

答案是:偶然。只是因为您在特定硬件上运行它。但是从C的角度来看它不应该。

这是一个如何使代码难以阅读和理解并因此导致错误的示例。

(dec & (highestOne >> i)) >> (highestOne - i - 1))

highestOne从一个非常大的数字开始,highestOne - i - 1将大于操作数大小,直到highestOne - i - 1小于sizeof(int)*8。这是一种未定义的行为。那么这段代码实际上是如何工作的呢?这只是因为shr指令的 x86 实现实际上以给定的位数移动操作数的模大小(以位为单位)。它不适用于大多数其他系统。

我敢打赌,原始代码的作者(从代码来看)是偶然做的。

正确的代码应该是(!!如果数字非零,则为一,否则为零):

void toBin(unsigned int dec) 
{         
                              
    unsigned int currentMask = 1 << (sizeof(dec) * CHAR_BIT - 1);
    for (; currentMask; currentMask >>= 1)
        printf("%d", !!(dec & currentMask));
    fflush(stdout);
}

int main(void)
{
    unsigned num;
    for(int x = 1; x < 10; x++)
    {   
        num = rand();
        toBin(num); printf(" (%u)\n", num);
    }
}

推荐阅读