Skip to content

Commit

Permalink
Fix bytesToNumber()
Browse files Browse the repository at this point in the history
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`.
  • Loading branch information
assafmo committed Nov 8, 2023
1 parent 1b6f942 commit f9a4c4c
Showing 1 changed file with 5 additions and 6 deletions.
11 changes: 5 additions & 6 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

0 comments on commit f9a4c4c

Please sign in to comment.