Enter any decimal number as an input. Also mention the bit position at which you want to check whether one is present or not. After that we first convert the given decimal number into binary number and then check the element at that given position and generate output.
Here is the source code of the Java Program to Check if a given Bit Position is set to One or not. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
public class Bit_Postion
public static void main(String args)
int n, m;
String x = "";
Scanner s = new Scanner(System.in);
System.out.print("Enter any Decimal Number:");
n = s.nextInt();
while(n > 0)
int a = n % 2;
x = a + x;
n = n / 2;
System.out.print("Enter the position where you want to check:");
int l = x.length();
m = s.nextInt();
if((l - m) >= 0 && (x.charAt(l - m) == '1'))
System.out.println("1 is present at given bit position");
System.out.println("0 is present at given bit position");
$ javac Bit_Postion.java $ java Bit_Postion Enter any Decimal Number:6 Enter the position where you want to check:2 1 is present at given bit position
Sanfoundry Global Education & Learning Series - 1000 Java Programs.