5

The binary for the decimal -805306368 is:

11111111111111111111111111111111 11010000000000000000000000000000

However, in Javascript I get the following:

var str = parseInt(-805306368).toString(2);
document.write(str);
-110000000000000000000000000000

Can anyone explain how to parse the 64 bit binary string from this decimal?

Teocci
  • 7,189
  • 1
  • 50
  • 48
StuR
  • 12,042
  • 9
  • 45
  • 66
  • 9
    There's a little semantic funny business in your question. `-805306368` in base 10 is exactly what you're getting: `-110000000000000000000000000000` in base 2. What you're looking for is the two's-complement representation. – Carl Norum Jun 07 '12 at 17:16

2 Answers2

13

JavaScript does not use the two's-complement representation, it uses the hyphen - character in front of the string to represent negative numbers. That's because two's-complement representation requires to know the length of bits. When turning a two's-complement number with a certain number of bits into one with more bits (e.g., when copying from a one-byte variable to a two-byte variable), the most-significant bit must be repeated in all the extra bits.

To get the expected result, you could invert each bit but it doesn't provide the result we want:

>>> (~-805306368).toString(2)
"101111111111111111111111111111"

Yet, JavaScript does all binary operations on 32-bit integers, so this won't work for bigger (or smaller) numbers and at least will be very confusing. So, you would need to implement your own formatting algorithm.

// example of 32-bit-conversion:
>>> (~parseInt("1111111111111111111111111111111",2)).toString(2)
"-10000000000000000000000000000000"
>>> (~parseInt("11111111111111111111111111111111",2)).toString(2)
"0"

My Implementation:

function get64binary(int) {
  if (int >= 0)
    return int
      .toString(2)
      .padStart(64, "0");
  else
    return (-int - 1)
      .toString(2)
      .replace(/[01]/g, d => +!+d) // hehe: inverts each char
      .padStart(64, "1");
}

console.log(get64binary(805306368))
console.log(get64binary(-805306368))
Teocci
  • 7,189
  • 1
  • 50
  • 48
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Yes, this is exactly what I was after. Thanks. – StuR Jun 07 '12 at 17:34
  • I've just realised the same. What I expect to be returned is "11010000000000000000000000000000" (the first 32 bits) – StuR Jun 07 '12 at 17:48
  • Ok, any pointers on implementing my own formatting algorithm - or an example in another language I can use for guidance? – StuR Jun 07 '12 at 18:00
  • Perfect, your function works great. Thanks very much for your help, if Carlsberg did answers.. :) – StuR Jun 07 '12 at 19:30
2

You can use parseInt() again. It has an optional second parameter, that enables you to specify the radix (or base) of the number in the string you are trying to parse.

Such as: parseInt("-110000000000000000000000000000", 2) // gives -805306368

Sune Rasmussen
  • 956
  • 4
  • 14