Reputation: 6368
If I want to convert a binary number to a 32 bit twos complementary number. What would be the correct way to do that in javascript
e.g. "10101010001000101110101000101110" -> -1440552402
and the other way around?
e.g. -1440552402 -> "10101010001000101110101000101110"
Upvotes: 1
Views: 175
Reputation: 64904
parseInt
with a base of 2 is almost enough, except that it doesn't treat the 32nd bit as a signbit.
But this works: parseInt(someString, 2) | 0
Going back to string, toString(2)
again almost works, but treats the sign in a way we don't want here, but this works: (x >>> 0).toString(2)
, the >>>0
makes it an unsigned integer.
Upvotes: 5