c - 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的角度来看它不应该。
这是一个如何使代码难以阅读和理解并因此导致错误的示例。
(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);
}
}
推荐阅读
- extractor - libarchive 完整提取器
- python - Tkinter 数据不打印
- html - 如何使用 .htaccess 将尾随“/”添加到网站
- python - 如何正确标准化地址类型
- javascript - 为什么我的 ForEach 执行而不被调用?反应器?
- spring-boot - JBoss EAP 7.1 + Spring Boot 应用程序:找不到约束“javax.validation.constraints.NotBlank”的验证器
- android - 如何将 gif 组合在一起制作一个场景?
- ajax - 使用primefaces进行wildfly迁移后tabView中的选项卡未更新
- r - 将同一 data.table 中的几组列相乘
- java - 我的数组只打印 0s--java