c - 向后打印无符号字符的二进制表示?
问题描述
这段代码究竟是如何工作的?我对第一个 for 循环感到困惑,因为二进制从 0 开始,只要它不等于 char 的二进制表示,它就会增加,那么二进制是 1 等等?
无符号字符 c; 整数二进制;
scanf("%c", &c);
getchar();
printf("The decimal representation is: %d\n", c);
for (binary = 0; (1<<binary)<=c; binary++){ // moving to the left
} // until binary code matches c
printf("The backwards binary representation is: ");
for (int i=0; i<binary; i++){ // since we know the size
printf("%d", ((c>>i)&1)); // 1s and 0s are shifted to right
}
printf("\n");
return 0;
解决方案
这个:
for (binary = 0; (1<<binary)<=c; binary++)
简单地计算整数“c”中有多少有效位。
例如,如果“c”是二进制的 0101100,则最高有效位是右数第 6 个,“binary”将设置为 6。
如果“c”是二进制的 01,则最高有效位是右起第一个,“binary”将被设置为 1。
这段代码最大的问题是它几乎无用的注释。如果必须有评论,请替换:
/* moving to the left until binary code matches c */
有了这个:
/* Count number of significant bits.*/
注释应该说明代码存在的原因,而不是描述它是如何工作的。
像这样的评论没有任何目的:
/* since we know the size 1s and 0s are shift to right */
第二大问题是变量名。“二进制”具有误导性。将其称为“number_of_significant_bits”,代码几乎不需要任何注释。
推荐阅读
- android - Android - 矢量绘图可以存储 GIF 文件/动画图像吗?
- c# - 将对象的实例传递给以 Action<> 作为参数的方法
- ios - IP地址的https SSL?
- php - 如何正确转义嵌套在 CSV 列中的 JSON 对象中的字符串中的双引号?
- python - cam.release() 后网络摄像头灯仍然亮着
- scala - Scala 类型推理混乱:有还是没有?
- c++ - 在 C++08 中初始化对象以作为参数传递的首选语法是什么?
- javascript - React/D3:从孩子渲染图
- c# - 无法创建接口类型的实例
- html - 从 iframe 中的角度应用程序内部访问隐藏 div 的值