peterolson / BigInteger.js

An arbitrary length integer library for Javascript
The Unlicense
1.12k stars 187 forks source link

toString() returns different value to Number #173

Closed TommyBs closed 5 years ago

TommyBs commented 5 years ago

I'm playing around with big-integer and I'm not sure if I'm doing something wrong with some bitwise operations, but the value I see when doing a console.log on the bigInt and the toString() method are both slightly different. Any idea what's going on here?

function getShardIdForId(id) { let s = bigInt(id); s = s.shiftRight(46).and(0xFFFF) return s.value }

function getLocalIdForId(id) { let s = bigInt(id); s = s.shiftRight(0).and(0xFFFFFFFFF); return s.value; }

function getFullIdFor(local_id,shard_id) { let s = bigInt(shard_id); let l = bigInt(local_id); let r = bigInt(0) r = s.shiftLeft(46).or(l.shiftLeft(0)) return r }

console.log(getShardIdForId('241294423792285600')); //outputs 3429 console.log(getLocalIdForId('241294423792285600')); //outputs 7075744

console.log(getFullIdFor(7075733,3429)); //outputs
{ [Number: 241294423792285600] value: [ 2285589, 9442379, 2412 ], sign: false, isSmall: false }

console.log(getFullIdFor(7075733,3429).toString()); //outputs 241294423792285589

peterolson commented 5 years ago

I'm not sure what the issue is. What is the problem you are seeing? getFullIdFor(7075733,3429).toString() is "241294423792285589".

console.log(getFullIdFor(7075733,3429)); will output the internal object representation of it, but if you take the numbers from the value [ 2285589, 9442379, 2412 ] in reverse order it will be the same as "241294423792285589".

TommyBs commented 5 years ago

Sorry, I've seen what I've done. I was expecting it to ouput '241294423792285600' but I realised I'd put a different number into my getFullId function (7075733) instead of the 7075744, hence I thought I was getting an incorrect result with the toString() function... tired eyes