How can one read an integer bit by bit in Java?
Using bitwise operators:
int getBit(int n, int k) {
return (n >> k) & 1;
}
Explanation (in bits):
n
100010101011101010 (example)
n >> 5
000001000101010111 (all bits are moved over 5 spots, therefore
& the bit you want is at the end)
000000000000000001 (0 means it will always be 0,
= 1 means that it will keep the old value)
1
return (n >> k) & 1;
Here, n >> k
shifts the k
-th bit into the least significant position, and & 1
masks out everything else.
If lowest significant bit is bit number 0
:
return (n>>k)&1;
or use:
boolean getBit(int n, int k) {
return ((n >> k) & 1) == 1;
}
if you want a boolean value