0

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
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122

1 Answers1

2

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'));
Ry-
  • 218,210
  • 55
  • 464
  • 476
  • Thanks for the answer, it worked nicely. I was thinking that JS had some method that already transformed in 32 bit positions numbers, but padStart is the way – Felipe Tomazetti Sep 14 '22 at 12:07