If int
is 32-bit long, 1 << 31
invokes signed integer overflow, which is undefined behavior.
Consider making the value to deal with unsigned.
void pBinary(unsigned int x)
{
unsigned int y = 1u << 31;
for (int n = 0; n < 32; n++) {
x & y ? putchar('1') : putchar('0');
y >>= 1;
}
putchar('
');
}
It is safer to use types with defined size. Include inttypes.h
or stdint.h
to use uint32_t
.
void pBinary(uint32_t x)
{
uint32_t = UINT32_C(1) << 31;
for (int n = 0; n < 32; n++) {
x & y ? putchar('1') : putchar('0');
y >>= 1;
}
putchar('
');
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…