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?
Your version is wrong. When you execute
if it is non-zero, then you get an int with every bit except the
posbit zeroed out, because that is the number on the right side of the&operator. This obviously would only be 1 ifpos==0.This happens because the
&operator simply takes the bitwise and operation between corresponding bits in the twoints. Since1 << poshas a1bit in a position besides the lowest andtokencan presumably be anyint, the result can also have a1bit in a position other than the lowest, making it greater than1.