Java.lang Package Classes

Java Long - numberOfLeadingZeros() Method



The java.lang.Long.numberOfLeadingZeros() method returns the number of zero bits preceding the highest-order ("leftmost") one-bit in the two's complement binary representation of the specified long value. The method returns 64 if the specified value has no one-bits in its two's complement representation, in other words if it is equal to zero.

For all positive long values x:

  • floor(log2(x)) = 63 - numberOfLeadingZeros(x)
  • ceil(log2(x)) = 64 - numberOfLeadingZeros(x - 1)

Syntax

public static int numberOfLeadingZeros(long i)

Parameters

i Specify the value whose number of leading zeros is to be computed.

Return Value

Returns the number of zero bits preceding the highest-order ("leftmost") one-bit in the two's complement binary representation of the specified long value, or 64 if the value is equal to zero.

Exception

NA.

Example:

In the example below, the java.lang.Long.numberOfLeadingZeros() method returns the number of zero bits preceding the leftmost one-bit in the two's complement binary representation of the given long value.

import java.lang.*;

public class MyClass {
  public static void main(String[] args) {
    
    //creating a long value
    long x = 75; 

    //printing value of x, its binary 
    //representation and numberOfLeadingZeros
    System.out.println("The values of x is: " + x);
    System.out.print("The binary representation of x is: ");
    System.out.println(Long.toBinaryString(x));
    System.out.print("The numberOfLeadingZeros is: ");
    System.out.println(Long.numberOfLeadingZeros(x));
  }
}

The output of the above code will be:

The values of x is: 75
The binary representation of x is: 1001011
The numberOfLeadingZeros is: 57

❮ Java.lang - Long

5