19 Aug Integer.lowestOneBit() method in Java
To understand the concept of Integer.lowestOneBit(), let’s say we have a decimal value:
1 2 3 |
155 |
The Binary of 155 is:
1 2 3 |
10011011 |
The lowest one bit is at position 1, therefore the lowestOneBit() method returns a single bit with the position of the rightmost one-bit value. The value returned is int.
Example 1
Following is an example to get the position of rightmost one-bit using Integer.lowestOneBit():
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public class Example { public static void main(String []args){ // decimal value int a = 5; System.out.println("Decimal Value = "+a); // binary value System.out.println("Binary Value = "+Integer.toBinaryString(a)); // displaying the lowest one bit position System.out.println("Lowest one bit position = " + Integer.lowestOneBit(a)); } } |
Output
1 2 3 4 5 |
Decimal Value = 5 Binary Value = 101 Lowest one bit position = 1 |
Example 2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public class Example { public static void main(String []args){ // decimal value int a = 155; System.out.println("Decimal Value = "+a); // binary value System.out.println("Binary Value = "+Integer.toBinaryString(a)); // displaying the lowest one bit position System.out.println("Lowest one bit position = " + Integer.lowestOneBit(a)); } } |
Output
1 2 3 4 5 |
Decimal Value = 155 Binary Value = 10011011 Lowest one bit position = 1 |
Example 3
If the decimal value passes is 0, the lowestOneBit() method returns 0 as in the below example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public class Example { public static void main(String []args){ // decimal value int a = 0; System.out.println("Decimal Value = "+a); // binary value System.out.println("Binary Value = "+Integer.toBinaryString(a)); // displaying the lowest one bit position System.out.println("Lowest one bit position = " + Integer.lowestOneBit(a)); } } |
Output
1 2 3 4 5 |
Decimal Value = 0 Binary Value = 0 Lowest one bit position = 0 |
No Comments