Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Negative numbers to binary string in JavaScript

Anyone knows why javascript Number.toString function does not represents negative numbers correctly?

//If you try (-3).toString(2); //shows "-11" // but if you fake a bit shift operation it works as expected (-3 >>> 0).toString(2); // print "11111111111111111111111111111101" 

I am really curious why it doesn't work properly or what is the reason it works this way? I've searched it but didn't find anything that helps.

like image 959
fernandosavio Avatar asked Apr 22 '13 19:04

fernandosavio


People also ask

How do you pass negative values in JavaScript?

To use negative numbers, just place a minus (-) character before the number we want to turn into a negative value: let temperature = -42; What we've seen in this section makes up the bulk of how we will actually use numbers.

How do you turn a negative into a positive in JavaScript?

The first approach uses the Math. abs() method to convert the negative values to positive ones.

Does parseInt work with negative numbers JavaScript?

parseInt understands exactly two signs: + for positive, and - for negative.


2 Answers

Short answer:

  1. The toString() function takes the decimal, converts it to binary and adds a "-" sign.

  2. A zero fill right shift converts it's operands to signed 32-bit integers in two complements format.

A more detailed answer:

Question 1:

//If you try (-3).toString(2); //show "-11" 

It's in the function .toString(). When you output a number via .toString():

Syntax

numObj.toString([radix])

If the numObj is negative, the sign is preserved. This is the case even if the radix is 2; the string returned is the positive binary representation of the numObj preceded by a - sign, not the two's complement of the numObj.

It takes the decimal, converts it to binary and adds a "-" sign.

  1. Base 10 "3" converted to base 2 is "11"
  2. Add a sign gives us "-11"

Question 2:

// but if you fake a bit shift operation it works as expected         (-3 >>> 0).toString(2); // print "11111111111111111111111111111101" 

A zero fill right shift converts it's operands to signed 32-bit integers. The result of that operation is always an unsigned 32-bit integer.

The operands of all bitwise operators are converted to signed 32-bit integers in two's complement format.

like image 186
Daan Avatar answered Sep 17 '22 08:09

Daan


-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.

http://en.wikipedia.org/wiki/Two%27s_complement

http://en.wikipedia.org/wiki/Logical_shift

like image 31
Steve Wang Avatar answered Sep 18 '22 08:09

Steve Wang