peterolson / BigInteger.js

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

Convert hex string Error #237

Closed chezhe closed 1 year ago

chezhe commented 1 year ago

When I create BigInteger from 0x428a2f98d728ae22, got below error:

Invalid integer: 0x428a2f98d728a0000000000000000000000

Because BigInteger.js miss handling e as a hex number.

peterolson commented 1 year ago

That's the incorrect way to pass a hex number. You can use the radix argument:

bigInt("428a2f98d728a0000000000000000000000", 16)

chezhe commented 1 year ago

If pass params like this:

bigInt("428a2f98d728ae22", 16)

It's a hex number, the e(abcdef are valid character in hex number) mean 14, not 10**22. The logic here doesn't cover above condition. https://github.com/peterolson/BigInteger.js/blob/master/BigInteger.js#L1364

peterolson commented 1 year ago
bigInt("428a2f98d728ae22", 16).toString()
// "4794697086780616226"

There's no issue here. e is interpreted correctly if you pass the radix argument. It goes into the parseBase function instead of the parseStringValue function.

antondalgren commented 1 year ago

It should allow the creation of large hex values on the format "0x428a2f98d728ae22" if it's supposed to work as a polyfill to the native BigInt

var bigInt = require("big-integer");

console.log(BigInt("0x428a2f98d728ae22"));
console.log(bigInt("0x428a2f98d728ae22"));
node index.js
4794697086780616226n
Error: Invalid integer: 0x428a2f98d728a0000000000000000000000
peterolson commented 1 year ago

The API of this library was created before the native BigInt existed, so there is no goal to match their API exactly, and doing so would introduce breaking changes.

Hex strings are already supported using the radix argument. I don't see a compelling reason to add support for a magic 0x prefix. In my opinion, bigInt("428a2f98d728ae22", 16) is more explicit and cleaner than bigInt("0x428a2f98d728ae22").

pke commented 4 months ago

@peterolson I get you point, but then please don't state this lib acts as light polyfill for native BigInt, which it does not if it does not support the natives ctor arguments. I have monkeypatched the ctor now to support natives hex notation (which is hideous, yes)