Reference Materials
Certification Courses
Created with over a decade of experience and thousands of feedback.
JavaScript Math clz32()
In this tutorial, you will learn about the JavaScript Math.clz32() method with the help of examples.
The clz32() method converts the specified number into 32-bit binary representation and returns the number of leading zero bits.
Example
// converts 5 to 00000000 00000000 00000000 00000101
// returns the leading 0 bits
let value = Math.clz32(5);
console.log(value);
// Output: 29
clz32() Syntax
The syntax of the Math.clz32() method is:
Math.clz32(number)
Here, clz32() is a static method. Hence, we are accessing the method using the class name, Math.
clz32() Parameter
The Math.clz32() method takes in a single parameter:
number- value whose leading zero bits is to be calculated (in 32-bit representation)
clz32() Return Value
The clz32() method returns:
- number of 0 bits 32-bit binary representation of the number
Example 1: JavaScript Math.clz32()
// leading zero bits of 0
let value1 = Math.clz32(2);
console.log(value1);
// leading zero bits of 100
let value2= Math.clz32(210);
console.log(value2);
// leading zero bits of 1000
let value3 = Math.clz32(1200);
console.log(value3);
// Output:
// 30
// 24
// 21
Here, Math.clz32() converts the specified number into its 32-bit binary representation and counts the leading 0.
1. Math.clz32(2)
- 32-bit representation: 00000000 00000000 00000000 00000010
- Number of leading zero: 30
2. Math.clz(210)
- 32-bit representation: 00000000 00000000 00000000 11010010
- Number of leading zero: 24
3. Math.clz(1200)
- 32-bit representation: 00000000 00000000 00000100 10110000
- Number of leading zero: 21
Example 2: Math.clz32() with Boolean Values
// clz32() with boolean value - true
let value1 = Math.clz32(true);
console.log(value1);
// clz32() with boolean value - false
let value2 = Math.clz32(false);
console.log(value2);
// Output:
// 31
// 32
Here, we have used the clz32() method with boolean values. JavaScript treats boolean values true as 1 and false as 0.
So, the method calculates the leading zero bits for value 1 and 0 respectively.
Example 3: Math.clz32() with a Non-Numeric Argument
// leading 0 bits of a string
let value = Math.clz32("Harry");
console.log(value);
// Output: 32
In the above example, we have tried to count the leading zeroes of the string "Harry".
clz32() will first convert the string "Harry" to its corresponding 32-bit binary format and treat it as a 0.
Hence, we get 32 as the output.
Also Read: