barlop - 3 months ago 17

Javascript Question

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

Rather like this question, but for javascript.

Print an integer in binary format in Java

Answer

```
function dec2bin(dec){
return (dec >>> 0).toString(2);
}
```

Here is the 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.

**Added example from barlop-**

```
(-3 >>> 0).toString(2))
```

will print

```
11111111111111111111111111111101
```

**Further additional point from barlop**

I notice that `(3).toString(2)`

or `(3>>>0).toString(2)`

, gives the result of 11, though the correct 2s complement, is 011.

In 2s complement, positive binary numbers are meant to start with at least one leading zero (more is unnecessary), but they should have at least the one zero. Negative numbers must start with a 1 (more 1s on the far left are ok but unnecessary).

So, `(-3>>>0).toString(0)`

does work for positive or negative, but in the positive case, you may want to add a leading 0 to the far left of the result. You may also want to remove superfluous 1s from the far left of negative numbers, leaving just a single 1. But really in 2s complement, positive numbers starting with 1 is a 'no no', it's wrong. So for positive numbers, add a leading zero to that result, if you want technically correct 2s complement.

**EDIT**:

(Note added by barlop, to answerer's edit)

The above works fine, but for the sake of commenter "Magus", or anybody else that is extracting a number from a textbox. In that situation, they will be getting a string and will have to convert that to an integer in order to do any arithmetic operation on it. So for anybody very new to javascript and getting a their input from a textbox, they can use parseInt to convert it, the following example of use of parseInt is relevant in that situation. The function

`dec2bin`

expects an integer argument`dec`

. So if you have a string you should convert it using`parseInt(myString, 10)`

. Here and here explains why use the second parameter of`parseInt`

function.