首页 > 解决方案 > 向后打印无符号字符的二进制表示?

问题描述

这段代码究竟是如何工作的?我对第一个 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;

标签: cbinarybit-manipulationbitwise-operators

解决方案


这个:

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”,代码几乎不需要任何注释。


推荐阅读