Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
integer
binary
communitycreator

What is Integer.highestOneBit() in java?

abhilash

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The highestOneBit() method of the Integer class is a static method used to calculate an integer value with no more than a single one-bit in the highest-orderleftmost one-bit of the supplied integer value. The method returns zero if the supplied values’ twos complement binary representation has no one-bits, i.e. if it is equal to zero.

Example

Let’s understand this method with the help of an example.

  • int value: 123
  • Binary representation of the int value: 1111011

The highest one-bit of 123 in its binary representation is at position six.

Now, the highest one-bit value can be calculated using the formula below:

highest-one-bit-value = 2indexoftheleftmostonebit2^{ index-of-the-left-most-one-bit} .

The highest one-bit value for 123 is 2 ** 6 = 64

%0 node_1631371704871 1 node_1631371744772 1 node_1631371731692 1 node_1631371742476 1 node_1 0 node_2 1 node_3 1
Highest One Bit Position for 123

Syntax


public static int highestOneBit(int i)

Parameters

  • i: the maximum one-bit value that must be calculated.

Returns

The highestOneBit() method returns the single one-bit int value in the highest-order one-bit of the provided value, or zero if the specified value is zero.

Code

In the code below, we use the highestOneBit method on different integer values.

public class Main{
private static void highestOneBit(int number){
System.out.println("Binary Representation of " + number + " - " + Integer.toBinaryString(number));
System.out.println("Highest One bit integer of " + number + " - "+ Integer.highestOneBit(number));
}
public static void main(String[] args){
highestOneBit(123);
System.out.println("----------");
highestOneBit(0);
System.out.println("----------");
highestOneBit(7);
}
}

RELATED TAGS

java
integer
binary
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring