diff --git a/src/utils.test.ts b/src/utils.test.ts new file mode 100644 index 0000000..107571e --- /dev/null +++ b/src/utils.test.ts @@ -0,0 +1,23 @@ +import { numberToBytes, bytesToNumber } from './utils'; + +describe('decrypt', () => { + it('converts a number to bytes', async () => { + const value = 28482; + const bytes = numberToBytes(value); + expect(bytes).toEqual(new Uint8Array([111, 66])); + + const value2 = 255; + const bytes2 = numberToBytes(value2); + expect(bytes2).toEqual(new Uint8Array([255])); + }); + + it('converts bytes to number', async () => { + const value = new Uint8Array([23, 200, 15]); + const bytes = bytesToNumber(value); + expect(bytes).toBe(1558543); + + const value2 = new Uint8Array(); + const bytes2 = bytesToNumber(value2); + expect(bytes2).toBe(0); + }); +}); diff --git a/src/utils.ts b/src/utils.ts index a24bda6..ce6de12 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -21,14 +21,17 @@ export const numberToBytes = (uint32Value: number) => { return byteArray; }; -export const bytesToNumber = (byteArray: Uint8Array): number => { - let uint32Value = 0; - - for (let i = 0; i < byteArray.length; i++) { - uint32Value |= byteArray[i] << (8 * (byteArray.length - 1 - i)); +export const bytesToNumber = function (byteArray: Uint8Array): number { + if (!byteArray || byteArray?.length === 0) { + return 0; } - return uint32Value; + const length = byteArray.length; + + const buffer = Buffer.from(byteArray); + const result = buffer.readUIntBE(0, length); + + return result; }; export const isAddress = function (address: string) {