这段代码究竟是如何工作的?我对第一个for循环感到困惑,因为二进制从0开始,只要它不等于它将增加的char的二进制表示,那么二进制是1,依此类推?
unsigned char c; int binary;
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位,“二进制”将被设置为6。
如果二进制“c”为01,则最高位是右起第一个,“二进制”将设置为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”,代码几乎不需要任何注释。