From f9a4c4c714bc23de77d400d85f163852df3d54bd Mon Sep 17 00:00:00 2001 From: Assaf Morami Date: Wed, 8 Nov 2023 14:41:05 +0200 Subject: [PATCH] Fix `bytesToNumber()` This fixes `bytesToNumber()` to always return the result as an unsigned integer. Example: `byteArray` holds the value `2^32 - 3`, which is `11111111111111111111111111111101` in binary. The old implementation uses the `number` type, which is a signed integer, to calculate intermediate values. And because the most significant bit (MSB) is turned on, it interprets this as a negative number and returns `-3`. --- src/utils.ts | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/utils.ts b/src/utils.ts index a24bda6..37de02f 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -21,14 +21,13 @@ export const numberToBytes = (uint32Value: number) => { return byteArray; }; -export const bytesToNumber = (byteArray: Uint8Array): number => { - let uint32Value = 0; +export const bytesToNumber = function (byteArray: Uint8Array): number { + const length = byteArray.length; - for (let i = 0; i < byteArray.length; i++) { - uint32Value |= byteArray[i] << (8 * (byteArray.length - 1 - i)); - } + const buffer = Buffer.from(byteArray); + const result = buffer.readUIntBE(0, length); - return uint32Value; + return result; }; export const isAddress = function (address: string) {