[英]Determining number of set bits in a char
如果將每個單元存儲為設置位,則該程序應確定在變量c_val
的值中存儲了多少個單元。 我的問題是:作者為什么寫if (c % 2 == 1) count++;
然后轉移c
與此聲明的權利c = c >> 1;
?
#include <stdio.h>
#include <cstdlib>
int main(){
unsigned char c_val;
printf("char value = ");
scanf("%c", &c_val);
int count = 0;
unsigned char c = c_val;
while(c){
if (c % 2 == 1) count++;
c = c >> 1;
}
printf("%d bits are set", count);
system("pause");
}
char類型的數據大小始終為一個字節 -無例外。 但是,此代碼將計算c_val中的popcount (即1位的c_val
。
我們可以翻譯相關的代碼
while (c) {
if (c % 2 == 1) count++;
c = c >> 1;
}
至
while (c != 0) {
if (c & 0x1 == 1) count++; /* if the rightmost bit of c is 1, then count++ */
c = c / 2;
}
我所做的最后一個更改之所以有效,是因為將無符號整數數據類型(在本例中為unsigned char
)右移等效於以2舍入為零的語義。
我們可以將c
看作是位的傳送帶-零位從左邊進來,而一位在每次循環迭代中從右邊掉落。 如果最右邊的位是1,我們將計數加1,否則計數保持不變。 因此,一旦c
用零位填充,我們就知道已經對所有一位進行了計數,准確地對了一位進行count
,因此count
包含了c_val
中一位的數量。
這根本不是確定char
類型實例的“大小”的函數,而是確定字符中設置為1的位數的功能。
表達方式
c % 2 == 1
確定最低有效位是否為1。
移位使倒數第二位進入最后位置,因此可以對其進行測試。
while (c)
的條件意味着保持計數1並移位直到整個字節全為零。
您的代碼只是編碼char c中的1位。 “ c%2 === 1”檢查“ c”中的最后一位是否為1。因此,我們必須使用“ c = c >> 1”將“ c”中的其他位移至最后位置。
其他方法也可以這樣做:
#include <stdio.h>
#include <conio.h>
unsigned int f (unsigned int a , unsigned int b);
unsigned int f (unsigned int a , unsigned int b)
{
return a ? f ( (a&b) << 1, a ^b) : b;
}
int bitcount(int n) {
int tot = 0;
int i;
for (i = 1; i <= n; i = i<<1)
if (n & i)
++tot;
return tot;
}
int bitcount_sparse_ones(int n) {
int tot = 0;
while (n) {
++tot;
n &= n - 1;
}
return tot;
}
int main()
{
int a = 12;
int b = 18;
int c = f(a,b);
printf("Sum = %d\n", c);
int CountA = bitcount(a);
int CountB = bitcount(b);
int CntA = bitcount_sparse_ones(a);
int CntB = bitcount_sparse_ones(b);
printf("CountA = %d and CountB = %d\n", CountA, CountB);
printf("CntA = %d and CntB = %d\n", CntA, CntB);
getch();
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.