bnToU8a supports endian (#87)

* bnToU8a supports endian

* Update with new bn.js flow
This commit is contained in:
Jaco Greeff
2018-02-13 14:30:10 +01:00
committed by GitHub
parent 05b5d600bf
commit f79d7fe68e
5 changed files with 29 additions and 11 deletions
+17 -5
View File
@@ -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;
};
+6
View File
@@ -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]));
});
});