Skip to content

Commit

Permalink
Merge pull request #42 from assafmo/fix-bytesToNumber-to-return-uint
Browse files Browse the repository at this point in the history
Fix `bytesToNumber()`
  • Loading branch information
immortal-tofu authored Nov 10, 2023
2 parents 1b6f942 + 35dc65d commit 7b1f4b1
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 6 deletions.
23 changes: 23 additions & 0 deletions src/utils.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
15 changes: 9 additions & 6 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

0 comments on commit 7b1f4b1

Please sign in to comment.