Skip to content
Advertisement

Negative or Positive Number to 32 Bit Binary Data in JS

I want to convert a number to 32 Bit binary data. When I try to convert a number to 16 bit or 8 bit data, there is no any problem. But When I try 32 Bit, result is not correct.

8 Bit example:

-1 & 255 //result -> 255 or -1 & 0xFF //result -> 255

16 Bit example:

-1 & 65535 //result -> 65535 or -1 & 0xFFFF //result -> 65535

Wrong result in 32 Bit

-1 & 4294967295 //result -> -1 or -1 & 0xFFFFFFFF //result -> 4294967295

My expectation in 32 bit, result is 4294967295. -1 is not a correct answer.

How can solve my problem. Thanks

Advertisement

Answer

I found answer of my question.

this is not working for 32 bit

-1 & 4294967295

this is working for 32 bit

-1 >>> 0 //result -> 4294967295

but I don’t understand the reason of this error.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement