gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:02:48 26 4
gpt4 key购买 nike

这段代码到底是如何工作的?我对第一个 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”,代码几乎不需要任何注释。

关于c - 向后打印无符号字符的二进制表示形式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55291327/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com