0

I want to transfer the following python code to javascript:

def conv_2c(val, bits):
   return ((1 << bits)+val)



function conv_2c(val, bits){ 
    return ((1 << bits)+val);
}

In Python print(conv_2c(-944,64)) gives me 18446744073709550672 , while in JS console.log(conv_2c(-944,64)); gives me -943 . Why is there a difference?? Is this something to worry about (do the numbers really differ?) or is it a thing of how Python or JS print negative/ two's complement numbers?

poke
  • 369,085
  • 72
  • 557
  • 602
user2224350
  • 2,262
  • 5
  • 28
  • 54
  • 3
    Bitshifting in JavaScript is always done in a 32 bit numbers. So big values can and will overflow. – VLAZ Nov 29 '16 at 22:31
  • sorry, I edited my post... So is it possible to handle such big numbers in javascript? – user2224350 Nov 29 '16 at 22:50
  • 1
    No, JavaScript numbers are [IEEE 754 floats](https://en.wikipedia.org/wiki/IEEE_floating_point), so the largest representable integer without loosing precision is [9007199254740991](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER). – poke Nov 29 '16 at 22:53
  • 1
    ^ Although there are [libraries that exist](http://mathjs.org/docs/datatypes/bignumbers.html) to handle higher precision numbers. – Mike Cluck Nov 29 '16 at 22:54
  • @poke then again, you will NOT be able to bitshift numbers that big - the biggest one you will be able to do is 2147483647 (2^31 - 1). If you go over, you immediately get the wrong result due to an overflow. – VLAZ Nov 29 '16 at 22:58
  • @vlaz Never said otherwise. My “no” in that comment was in response to “is it possible to handle such big numbers in javascript”. That doesn’t take into account the *additional* restrictions on bit shifting. – poke Nov 29 '16 at 23:07

0 Answers0