1

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.

1 Answers1

0

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) % 2 == 0;
    }
}
// Output: false
CcmU
  • 780
  • 9
  • 22