Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix bytesToNumber() #42

Merged
merged 3 commits into from
Nov 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading