我在下面包含了整个代码,但我唯一想知道的是setBit
函数。x = 1 << bitNum
只会将 0001 向左移动很多空格,具体取决于数字bitNum
是多少,但我不明白最后一行(*u |= x)
为什么在这里使用指针?
#include <stdio.h>
typedef unsigned int uint;
int checkBit(uint u, uint bitNum);
void setBit(uint* u, uint bitNum);
int countOnes(uint u);
int main()
{
uint xxx, bitNumber;
printf("\n Enter decimal integer xxx: ");
scanf("%u", &xxx);
printf("\n xxx in decimal: %u", xxx);
printf("\n xxx in hex: %x", xxx);
////// Test countOnes function /////////////
printf("\n Number of ones in xxx: %d", countOnes(xxx));
////// Test checkBit function /////////////
printf("\n Enter bit to check: ");
scanf("%u", &bitNumber);
printf("\n Bit %d is %d", bitNumber, checkBit(xxx, bitNumber));
printf("\n Enter bit to check: ");
scanf("%u", &bitNumber);
printf("\n Bit %d is %d", bitNumber, checkBit(xxx, bitNumber));
////// Test setBit function /////////////
printf("\n Enter bit to set: ");
scanf("%u", &bitNumber);
printf("\n Setting bit %d of xxx", bitNumber);
setBit(&xxx, bitNumber);
printf("\n xxx in hex: %x", xxx);
printf("\n");
return 0;
}
int countOnes(uint u)
{
int bitCount;
for(bitCount = 0; u; u = u >> 1)
{
bitCount += u & 1;
}
return bitCount;
}
void setBit(uint* u, uint bitNum)
{
int x;
x = 1 << bitNum;
*u |= x;
}
int checkBit(uint u, uint bitNum)
{
int x = u >> bitNum;
if(x & 1 == 1)
return 1;
else
return 0;
}