Skip to content

Commit

Permalink
Merge pull request #4 from zsqk/feat-u8a-int
Browse files Browse the repository at this point in the history
feat: add u8aToInt, intToU8a
  • Loading branch information
iugo committed Aug 9, 2022
2 parents 9b9fd4c + 471a189 commit c3b6705
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
15 changes: 15 additions & 0 deletions js/int.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { assertEquals } from 'https://deno.land/[email protected]/testing/asserts.ts';
import { intToU8a, u8aToInt } from './int.ts';

Deno.test('u8aToInt', () => {
assertEquals(u8aToInt(new Uint8Array([0, 0, 0, 25])), 25);
assertEquals(u8aToInt(new Uint8Array([1, 145])), 401);
});

Deno.test('intToU8a', () => {
assertEquals(intToU8a(25, { l: 4 }), new Uint8Array([0, 0, 0, 25]));
assertEquals(intToU8a(401, { l: 2 }), new Uint8Array([1, 145]));
assertEquals(intToU8a(1048576, { l: 1 }), new Uint8Array([0]));
assertEquals(intToU8a(25, { l: 'auto' }), new Uint8Array([25]));
assertEquals(intToU8a(401, { l: 'auto' }), new Uint8Array([1, 145]));
});
53 changes: 53 additions & 0 deletions js/int.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/**
* Uint8Array to number
* - `[ 0, 0, 0, 25 ]` => `25`
* - `[ 1, 145 ]` => `401`
* @param u8a 一个 Uint8Array 格式的数据.
* @returns 一个十进制整数.
*/
export function u8aToInt(u8a: Uint8Array): number {
let n = 0;
for (let i = 0; i < u8a.length; i++) {
const m = u8a.length - i - 1;
if (m === 0) {
n += u8a[i];
} else {
n += m * 256 * u8a[i];
}
}
return n;
}

/**
* int(number) to Uint8Array
* @param int 一个十进制整数.
* @returns 一个 Uint8Array 格式的数据.
*/
export function intToU8a(
int: number,
{ l = 'auto' }: { l?: number | 'auto' } = {},
): Uint8Array {
let left = int;
if (typeof l === 'number') {
const arr: number[] = Array(l);
for (let i = l - 1; i > -1; i--) {
const n = left % 256;
arr[i] = n;
left = Math.trunc(left / 256);
}
if (left > 0) {
console.warn(`intToU8a left ${left} * 256 * ${l}`);
}
return new Uint8Array(arr);
}
const arr: number[] = [];
do {
const n = left % 256;
arr.push(n);
left = Math.trunc(left / 256);
if (left === 0) {
break;
}
} while (true);
return new Uint8Array(arr.reverse());
}

0 comments on commit c3b6705

Please sign in to comment.