How can one read an integer bit by bit in Java?

I would like to take an int as input, and return the kth bit.

int getBit(int n, int k){ return kth bit in n;
}

How would i do this?

5 Answers

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
5
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

You can also use the module property for this. If your number is even the lowest significant bit is zero, otherwise (odd) is one.

return (n>>k)%2;

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like