How do I convert an integer in JavaScript to a 32bits?

Viewed 25

I have some numbers (base 10) that I want to convert to a 32 bits(base 2), I have tried a lot of things, I found out the >>> operator, but apparently it only converts negative numbers to a base 10 the equivalent of the 32 bits, instead of base 2

const number = 3

const bitNumber = 1 >>> 0

console.log(bitNumber) /// 1
1 Answers

The numbers are always stored as bits internally. It’s console.log that converts them to a string, and the string conversion uses decimal by default.

You can pass a base to Number.prototype.toString:

console.log(bitNumber.toString(2));

and display as many bit positions as you want:

console.log(bitNumber.toString(2).padStart(32, '0'));
Related