Reputation: 54094
I am looking some part of code that is supposed to get a single bit from an int.
It is as follows:
private int getBit( int token, int pos){
return ( token & ( 1 << pos ) ) != 0 ? 1 : 0;
}
My question is why doesn't it do it the following (simpler) way?
return token & ( 1 << pos );
I expect that it will also return a 0
or 1
.
Am I wrong on this? Is the second (mine) version wrong?
Upvotes: 0
Views: 84
Reputation: 47739
Of course, you can use something on the order of
(token >> pos) & 1
Upvotes: 2
Reputation: 20297
Your version is wrong. When you execute
return token & ( 1 << pos );
if it is non-zero, then you get an int with every bit except the pos
bit zeroed out, because that is the number on the right side of the &
operator. This obviously would only be 1 if pos==0
.
This happens because the &
operator simply takes the bitwise and operation between corresponding bits in the two int
s. Since 1 << pos
has a 1
bit in a position besides the lowest and token
can presumably be any int
, the result can also have a 1
bit in a position other than the lowest, making it greater than 1
.
Upvotes: 2
Reputation: 1519
Your version does not return the value of the bit at position pos. It returns the value 0 or 2^(pos-1).
Upvotes: 3
Reputation: 206841
Your version returns 0 or 1<<pos
.
That won't matter if it is used in boolean context. But it might otherwise.
Upvotes: 2