JavaScript Math.clz32() Method



The JavaScript Math.clz32() method is used to return the number of leading zero bits in the 32-bit binary representation of the provided number. The full form of clz32 is CountLeadingZeroes32.

The "Leading Zero Bits" are the zeros at the beginning (to the left) of a binary representation of a number. For example, the binary representation of 12 is '00000000000000000000000000001100'. It has 28 leading zero bits.

Syntax

Following is the syntax of JavaScript Math.clz32() method −

Math.clz32(x)

Parameters

This method accepts only one parameter. The same is described below −

  • x: The number for which to count the leading zeros.

Return value

This method returns the number of leading zero bits in the 32-bit binary representation of the provided number.

Example 1

In the following example, we are using the JavaScript Math.clz32() method to retrieve the leading zeros for the binary value of 16 −

<html>
<body>
<script>
   const result = Math.clz32(16); //"00000000000000000000000000010000"
   document.write(result);
</script>
</body>
</html>

Output

After executing the above program, it returns 27 as result.

Example 2

Here, we are passing a floating-point number 3.14(considering only the integer part) and fetching the leading zeros −

<html>
<body>
<script>
   const result = Math.clz32(3.14); //00000000000000000000000000000011
   document.write(result);
</script>
</body>
</html>

Output

If we execute the program, it returns 30 as result.

Example 3

In this example, we are passing 0 or -0 as arguments to this method −

<html>
<body>
<script>
   const result1 = Math.clz32(0);
   const result2 = Math.clz32(-0);
   document.write(result1, "<br>", result2);
</script>
</body>
</html>

Output

The binary representation of 0 is "00000000000000000000000000000000", and there are 32 leading zeros.

Advertisements