![](/img/trans.png)
[英]UNDERSTANDING how to count trailing zeros for a number using bitwise operators in C
[英]Using Bitwise Operators to Count the Number of 1's
我正在使用C語言中的按位運算符編寫程序。它是用於學校作業的,目的是計算整數的位表示形式中1的數量,如果結果為偶數則打印“ Even”,如果結果為偶數則打印“ Odd”這很古怪。
我編寫了一個程序來遍歷每個位,並將輸入的整數與掩碼進行比較,並在每次按位AND運算符返回1時增加一個計數器變量。但是,該程序似乎並未在增加計數器變量。 這是代碼:
#include <stdio.h>
void bitsEvenOrOdd(int value);
int main(void) {
int integer;
printf("Enter an integer: ");
scanf("%d", &integer);
bitsEvenOrOdd(integer);
return 0;
}
void bitsEvenOrOdd(int value) {
unsigned int displayMask;
unsigned int i;
unsigned int counter;
counter = 0;
displayMask = 1 << 31;
for (i = 0; i < 32; i++) {
if ((value & displayMask) == 1) {
counter++;
}
value <<= 1;
}
if ((counter % 2) == 0) {
printf("The total number of 1's in the bit representation is even.\n");
}
else {
printf("The total number of 1's in the bit representation is odd.\n");
}
}
任何建議或技巧的話,我們將不勝感激。 謝謝!
if ((value & displayMask) == 1) {
考慮此操作。 displayMask
是0x80000000。 按位在該數字與任何其他數字之間只能是0x80000000或0。您正在將其與1進行比較。
比較它是否等於0或(我建議這樣做),檢查最低位設置並向右移動而不是向左移動。
您正在轉移錯誤的方式:
value >>= 1;
假設int
是32位,則displayMask = 1 << 31
設置了最高位,但是在displayMask
。 當您將該值左移1時,單個設置位將被移出,因此您的掩碼現在為0。
轉到右移。
value >>= 1;
您的比較也不正確:
if ((value & displayMask) == 1) {
僅當掩碼為1且低位設置為1時,這才成立。 相反,請檢查結果是否為非零:
if ((value & displayMask) != 0) {
看這行
if( (value & displayMask) == 1)
考慮當displayMask為2、4、8等時會發生什么
您應該檢查最低位以解決此問題。 考慮代碼中的以下更改
unsigned int counter;
counter = 0;
- displayMask = 1 << 31;
+ displayMask = 1;
for (i = 0; i < 32; i++) {
if ((value & displayMask) == 1) {
counter++;
}
- value <<= 1;
+ value >>= 1;
}
if ((counter % 2) == 0) {
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.