Write Java program to Find the position of MSB bit of an integer number


The code is taking an integer input from the user, and then counting the position of the Most Significant Bit (MSB) in the binary representation of the number.

It does this by initializing a variable pos to 0, and then right shifting the number by 1 bit at a time until it becomes zero. Each time the number is shifted, the pos variable is incremented by 1. The final value of pos - 1 is the position of the MSB bit.

For example, if the input is 13 which has a binary representation of 1101, the program will output 3 since the MSB bit is at position 3 from the right.

Source Code

import java.util.Scanner;
public class MSBbit_IntegerNum
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
 
		int num = 0;
		int pos = 0;
 
		System.out.printf("Enter the Number :");
		num = input.nextInt();
 
		while (num > 0)
		{
			pos++;
			num = num >> 1;
		}
		System.out.println("Position of MSB bit is : "+( pos - 1));
	}
}

Output

Enter the Number :23
Position of MSB bit is : 4

Example Programs