Manipulating bits of a character variable
My objective is to frame a char variable by assigning values to each bit, ie I need to assign 0's and 1's to each bit.
I did the following code:
char packet;
int bit;
packet &= ~(1 << 0);
packet |= (1 << 1);
printf("n Checking each bit of packet: n");
for(int x=0;x<2;x++)
{
bit = packet & (1 << x);
printf("nBit [%d] of packet : %d", x, bit);
}
But the output I am getting is:
Bit[0] of packet : 0 Bit[1] of packet : 2
What is the problem here?
There's no problem here, the output is correct.
Here's the reason:
When you set the value of packet with |= , the value is 10 which, in decimal, is 2. When you assign packet & (1 << x) to bit , you're actually assigning the value 2 ( 10 in binary).
Wikipedia entry:
To determine whether the second bit is 1, a bitwise AND is applied to it and another bit pattern containing 1 in the second bit:
0011 (decimal 3)
AND 0010 (decimal 2)
= 0010 (decimal 2)
If your intent is to simply check a boolean value of whether or not the bit has been set, simply cast it to a bool value.
(Hope that all made sense, I'm a little tired atm ;))
First thing:
char packet;
packet &= ~(1 << 0);
This is not reliable, since packet starts off with whatever was in memory last (ie garbage). 1 << 0 is just 1 . ~1 is ...111110. Anding that with packet will give a different answer each time, depending on what was in memory last; the only sure thing is that the last bit (ie least significant) will be set to 0 .
packet |= (1 << 1);
This just sets the second bit to 1 . So now packet is xxxxxx10 .
Your loop then goes over the first two bits; each bit is masked with packet & (1 << x) , but that only masks it, it does not move it around. So during the first iteration, 1 << x is 1 , and you get the first bit ( 0 ). The second iteration, 1 << x is 10 , or 2 in decimal. Anding xxxxxx10 with 10 gives 10 , which you promptly print out (it appears formatted as 2 ).
If you want to move the bit (in order to isolate it as a 0 or 1), you can use:
bit = (packet & (1 << x)) >> x;
Or the equivalent but more readable
bit = (packet >> x) & 1;
This will yield the (I'm assuming desired) output of 0 , 1 instead of 0 , 2 .
That output appears entirely expected. Bit 0 isn't set, Bit 1 is set. Perhaps you're after
bit = !!(packet & (1 << x));
...if you want to get an 0 or 1 result.
By the way, you should initialise packet - use of an uninitialised variable results in undefined behaviour.
上一篇: 挑战位操作过程
下一篇: 操作字符变量的位
