I'm working on a project in java recently and i would like to handle the bits of an integer so that i can check the i lsb of a number. I have found a lot of approaches but nothing that can handle properly...
Example
key= 4
Key 4
in binary is 100
I would like in some way to extract the 3rd LSB of 4
which is 1
.
Is there an algorithm that can do that?
Using bit-shifting and bitwise AND: (indexed from 0)
int getBit(int number, int index)
{
return (number >> index) & 1;
}
getBit(4, 2)
returns 1.
You can also use % 2
instead of & 1
.