繁体   English   中英

向后打印无符号字符的二进制表示形式?

[英]Printing the binary representation of an unsigned char backwards?

该代码如何工作? 我对第一个for循环感到困惑,因为二进制从0开始,只要它不等于char的二进制表示形式,它将增加,所以二进制是1,依此类推?

无符号字符c; int二进制

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM