Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert an integer to binary in JavaScript?

I’d like to see integers, positive or negative, in binary.

Rather like this question, but for JavaScript.

like image 987
barlop Avatar asked Mar 30 '12 08:03

barlop


People also ask

Does JavaScript use binary code?

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.

How do you convert a number to an integer in JavaScript?

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.


1 Answers

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.

like image 177
fernandosavio Avatar answered Sep 30 '22 15:09

fernandosavio