Search code examples
javabit-manipulationbit

How to check if a single bit in a given bit is 1 or 0?


How do I check if a number in bit number is one or zero? For example: Number given: 0b00001101 Position of bit index 0 = true Position of bit index 1 = false

I’m stuck on determining the position of the bit.


Solution

  • One way to check if a given position, say n, of the binary representation of the number is 0 is to shift the number n times and check the last digit shifted. In example

    public class Main {
        public static void main(String[] args) {
            System.out.println(checkPosition(Byte.parseByte(String.valueOf(3)),1));
        }
        // Return true if the given position is 0, false otherwise
        public static boolean checkPosition(Byte b, int position)    {
            return ((b.byteValue() >> position) & 1) == 0;
        }
    }
    // Output: false