I’d like to see integers, positive or negative, in binary.
Rather like this question, but for JavaScript.
JavaScript Uses 32 bits Bitwise Operands JavaScript stores numbers as 64 bits floating point numbers, but all bitwise operations are performed on 32 bits binary numbers. Before a bitwise operation is performed, JavaScript converts numbers to 32 bits signed integers.
In JavaScript parseInt() function (or a method) is used to convert the passed in string parameter or value to an integer value itself. This function returns an integer of base which is specified in second argument of parseInt() function.
function dec2bin(dec) { return (dec >>> 0).toString(2); } console.log(dec2bin(1)); // 1 console.log(dec2bin(-1)); // 11111111111111111111111111111111 console.log(dec2bin(256)); // 100000000 console.log(dec2bin(-256)); // 11111111111111111111111100000000
You can use Number.toString(2)
function, but it has some problems when representing negative numbers. For example, (-1).toString(2)
output is "-1"
.
To fix this issue, you can use the unsigned right shift bitwise operator (>>>
) to coerce your number to an unsigned integer.
If you run (-1 >>> 0).toString(2)
you will shift your number 0 bits to the right, which doesn't change the number itself but it will be represented as an unsigned integer. The code above will output "11111111111111111111111111111111"
correctly.
This question has further explanation.
-3 >>> 0
(right logical shift) coerces its arguments to unsigned integers, which is why you get the 32-bit two's complement representation of -3.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With