Skip to content

Commit

Permalink
Fix: Ensure correct hexadecimal representation for .toString('hex') a…
Browse files Browse the repository at this point in the history
…nd .toString(16) methods (#61)

* test: add hexadecimal conversion check for small integers

* fix: handle string representation for base in toString method

- Check if the argument is a string representation for the base.
- Set base to 16 if the argument is "hex".
  • Loading branch information
nnnoel authored Sep 11, 2023
1 parent 5412b07 commit 4474750
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
13 changes: 10 additions & 3 deletions cpp/MGBigNumberHostObject.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -333,9 +333,16 @@ namespace margelo
std::shared_ptr<MGBigNumber> thiz = thisValue.getObject(runtime).getHostObject<MGBigNumber>(runtime);

int base = 10;
if (!arguments[0].isUndefined() && arguments[0].isNumber())
{
base = (int)arguments[0].asNumber();
if (!arguments[0].isUndefined()) {
if (arguments[0].isNumber()) {
base = static_cast<int>(arguments[0].asNumber());
} else if (arguments[0].isString()) {
std::string argValue = arguments[0].getString(runtime).utf8(runtime);
if (argValue == "hex") {
base = 16;
}
// TODO: Add more conditions here if you support other string representations for bases.
}
}
int len = -1;
if (!arguments[1].isUndefined())
Expand Down
5 changes: 5 additions & 0 deletions example/src/Testing/bn-tests/constructor-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@ export function registerConstructorTests() {
it('should accept two-limb LE number', function () {
assert.equal(new BN(0x4123456, null, 'le').toString(16), '56341204');
});

it('should correctly convert number to hexadecimal', function () {
assert.equal(new BN(100).toString('hex'), '64');
assert.equal(new BN(100).toString(16), '64');
});
});

describe('with String input', function () {
Expand Down

0 comments on commit 4474750

Please sign in to comment.