[英]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.