简体   繁体   English

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

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

How exactly does this code work? 该代码如何工作? I'm confused about the first for loop since binary starts at 0 and as long as it is not equal to the binary representation of the char it will increase, so then binary is 1 and so on? 我对第一个for循环感到困惑,因为二进制从0开始,只要它不等于char的二进制表示形式,它将增加,所以二进制是1,依此类推?

unsigned char c; 无符号字符c; int binary; 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;

This: 这个:

for (binary = 0; (1<<binary)<=c; binary++)

simply counts how many significant bits are in the integer "c". 简单地计算整数“ c”中有多少有效位。

For instance, if "c" is 0101100 in binary, the most significant bit is the 6th from the right, and "binary" would be set to 6. 例如,如果“ c”为二进制的0101100,则最高有效位是从右数第6位,而“ binary”将被设置为6。

If "c" is 01 in binary, the most significant bit is the first from the right, and "binary" would be set to 1. 如果“ c”的二进制值为01,则最高有效位是从右开始的第一位,“ binary”将被设置为1。


The biggest problem with this code is its almost useless comments. 此代码的最大问题是其几乎无用的注释。 If there must be comments, replace this: 如果有评论,请替换为:

/* moving to the left until binary code matches c */

with this: 有了这个:

/* Count number of significant bits.*/

Comments should say why the code is there, not describe how it works. 注释应说明为什么存在该代码,而不是描述其工作方式。

Comments like this don't serve any purpose: 这样的注释没有任何作用:

/* since we know the size 1s and 0s are shift to right */

The second biggest problem is the variable names. 第二大问题是变量名。 "binary" is misleading. “二进制”具有误导性。 Call it "number_of_significant_bits" instead and the code almost doesn't need any comments. 改称它为“ number_of_significant_bits”,该代码几乎不需要任何注释。

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

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