以下にコード全体を含めましたが、私が疑問に思っているのは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;
}