3

Why a positive number operated with bitwise or 0 not always positive in Javascript

For example:

3391700000|0
-903267296

4260919000|0
-34048296

2884900000|0
-1410067296

I'm using chrome 64-bit on Linux

related to: https://stackoverflow.com/a/12837315/1620210

Community
  • 1
  • 1
Kokizzu
  • 24,974
  • 37
  • 137
  • 233

2 Answers2

2

Because JavaScript uses 32bit integers at most, but keep in mind every number is kind of a float in this language

If you want to truncate them to an unsigned 32bit value:

(3391700000|0) >>> 0
axelduch
  • 10,769
  • 2
  • 31
  • 50
1

In JavaScript, the operands of bitwise operators are converted to signed 32-bit integers in 2's complement format. Thats why you got some loss of data and the truncated values are sometimes negative because of signed two's complement representation.

You can refer to Why bitwise shift with 0 in JavaScript yields weird results in some cases thread which was asked by myself some time ago and some answers pointed out the possible issue with bitwise operators where your operands exceed 32-bit integers very comprehensively.

Community
  • 1
  • 1
TaoPR
  • 5,932
  • 3
  • 25
  • 35