Signed conversion on empty u8a (#1484)

This commit is contained in:
Jaco
2022-05-12 12:14:34 +03:00
committed by GitHub
parent 6914411232
commit 65939dbe9d
2 changed files with 38 additions and 9 deletions
+36 -7
View File
@@ -30,13 +30,42 @@ describe('u8aToBn', (): void => {
).toBe('3412');
});
it('converts empty', (): void => {
expect(
u8aToBn(
new Uint8Array(),
{ isLe: true }
).toString(16)
).toBe('0');
describe('empty creation', (): void => {
it('handles unsigned (le)', (): void => {
expect(
u8aToBn(
new Uint8Array(),
{ isLe: true }
).toString(16)
).toBe('0');
});
it('handles signed (le)', (): void => {
expect(
u8aToBn(
new Uint8Array(),
{ isLe: true, isNegative: true }
).toString(16)
).toBe('0');
});
it('handles unsigned (be)', (): void => {
expect(
u8aToBn(
new Uint8Array(),
{ isLe: false }
).toString(16)
).toBe('0');
});
it('handles signed (be)', (): void => {
expect(
u8aToBn(
new Uint8Array(),
{ isLe: false, isNegative: true }
).toString(16)
).toBe('0');
});
});
it('handles negative numbers (little-endian)', (): void => {
+2 -2
View File
@@ -26,7 +26,7 @@ import { objectSpread } from '../object/spread';
* ```
*/
export function u8aToBn (value: Uint8Array, options: ToBnOptions | boolean = {}): BN {
// NOTE: This is the same process as followed in the hex conversion
// NOTE: This is the same process as followed in the hextoBn conversion
// For Uint8Array, default to LE
const { isLe, isNegative } = objectSpread<ToBnOptions>(
{ isLe: true, isNegative: false },
@@ -36,7 +36,7 @@ export function u8aToBn (value: Uint8Array, options: ToBnOptions | boolean = {})
);
const bn = new BN(value, isLe ? 'le' : 'be');
return isNegative
return isNegative && value.length
? bn.fromTwos(value.length * 8)
: bn;
}