Interview Question


How do you check if the 5th bit is a 1 in a binary number


Interview Answer

1 Answer


We can use a mask: 16 is represented in binary as 100000 (with the 5th bit set to 1). To the check if the 5th bit is one, we just need to do a bit-wise and of the number with the mask: if (x & 16 > 0) { // the 5th bit is one } For a more general case, to know if the k th bit is set to 1, we can shift the bit: if ((x >> (k - 1)) & 1 > 0) { // the kth bit is one }

Anonymous on Jul 30, 2013

Add Answers or Comments

To comment on this, Sign In or Sign Up.