This is a Java Program to Check if a given Bit Position is set to One or not.
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.
import java.util.Scanner;
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");
}
else
{
System.out.println("0 is present at given bit position");
}
}
}
Output:
$ 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.
advertisement
advertisement
Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.
Related Posts:
- Practice BCA MCQs
- Practice Programming MCQs
- Apply for Computer Science Internship
- Apply for Java Internship
- Practice Information Technology MCQs