bnToU8a supports endian (#87)
* bnToU8a supports endian * Update with new bn.js flow
This commit is contained in:
@@ -11,22 +11,34 @@ const bnToHex = require('./toHex');
|
||||
|
||||
/**
|
||||
@name bnToU8a
|
||||
@signature bnToU8a (value?: BN | number, bitLength: number = -1): Uint8Array
|
||||
@signature bnToU8a (value?: BN | number, bitLength: number = -1, isLE: boolean = false): Uint8Array
|
||||
@summary Creates a Uint8Array object from a BN.
|
||||
@description
|
||||
`null`/`undefined`/`NaN` inputs returns an empty `Uint8Array` result. `BN` input values return the actual bytes value converted to a `Uint8Array`.
|
||||
`null`/`undefined`/`NaN` inputs returns an empty `Uint8Array` result. `BN` input values return the actual bytes value converted to a `Uint8Array`. Optionally convert using little-endian format if `isLE` is set.
|
||||
@example
|
||||
import { bnToU8a } from '@polkadot/util';
|
||||
|
||||
bnToU8a(new BN(0x1234)); // => [0x12, 0x34]
|
||||
*/
|
||||
module.exports = function bnToU8a (value?: BN | number, bitLength: number = -1): Uint8Array {
|
||||
module.exports = function bnToU8a (value?: BN | number, bitLength: number = -1, isLe: boolean = false): Uint8Array {
|
||||
// flowlint-next-line sketchy-null-number:off
|
||||
if (!value) {
|
||||
return new Uint8Array([]);
|
||||
}
|
||||
|
||||
return hexToU8a(
|
||||
bnToHex(bnToBn(value), bitLength)
|
||||
if (bitLength === -1) {
|
||||
return hexToU8a(
|
||||
bnToHex(bnToBn(value), bitLength)
|
||||
);
|
||||
}
|
||||
|
||||
const byteLength = Math.ceil(bitLength / 8);
|
||||
const output = new Uint8Array(byteLength);
|
||||
|
||||
output.set(
|
||||
bnToBn(value).toArray(isLe ? 'le' : 'be', byteLength),
|
||||
0
|
||||
);
|
||||
|
||||
return output;
|
||||
};
|
||||
|
||||
@@ -24,4 +24,10 @@ describe('bnToU8a', () => {
|
||||
bnToU8a(new BN(0x123456), 32)
|
||||
).toEqual(new Uint8Array([0x00, 0x12, 0x34, 0x56]));
|
||||
});
|
||||
|
||||
it('converts using little endian (as set)', () => {
|
||||
expect(
|
||||
bnToU8a(new BN(0x123456), 32, true)
|
||||
).toEqual(new Uint8Array([0x56, 0x34, 0x12, 0x00]));
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user