user2167582
user2167582

Reputation: 6368

How to perform twos complement and bitwise operations in javascript

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

Answers (1)

user555045
user555045

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

Related Questions