instagram

How to get the value of a bit at a certain position from a byte

Java get bit from particular position.

This is very simple, We are going to shift right up to certain position and going to do & operation with result.

Note : Bit count will start with 0 as same as array.

public class BitwiseFindBitAtPosition {

	public static void main(String[] args) {
		int n = 1387;
		System.out.println(Integer.toBinaryString(n));

		int position = 0;
		System.out.println("Bit at (" + position + ") is :" + getBitAtPosition(n, position));

		position = 2;
		System.out.println("Bit at (" + position + ") is :" + getBitAtPosition(n, position));
	}

	public static int getBitAtPosition(int n, int position) {
		int bit = (n >> position) & 1;
		return bit;
	}

}

Output :
10101101011
Bit at (0) is :1
Bit at (2) is :0

Share