Skip to content

Commit

Permalink
Added hex support for bigint (#1472).
Browse files Browse the repository at this point in the history
  • Loading branch information
ricmoo committed Apr 23, 2021
1 parent 3bb5fbf commit 4e9abfd
Showing 1 changed file with 9 additions and 3 deletions.
12 changes: 9 additions & 3 deletions packages/bytes/src.ts/index.ts
Expand Up @@ -190,15 +190,15 @@ export function isHexString(value: any, length?: number): boolean {

const HexCharacters: string = "0123456789abcdef";

export function hexlify(value: BytesLike | Hexable | number, options?: DataOptions): string {
export function hexlify(value: BytesLike | Hexable | number | bigint, options?: DataOptions): string {
if (!options) { options = { }; }

if (typeof(value) === "number") {
logger.checkSafeUint53(value, "invalid hexlify value");

let hex = "";
while (value) {
hex = HexCharacters[value & 0x0f] + hex;
hex = HexCharacters[value & 0xf] + hex;
value = Math.floor(value / 16);
}

Expand All @@ -210,6 +210,12 @@ export function hexlify(value: BytesLike | Hexable | number, options?: DataOptio
return "0x00";
}

if (typeof(value) === "bigint") {
value = value.toString(16);
if (value.length % 2) { return ("0x0" + value); }
return "0x" + value;
}

if (options.allowMissingPrefix && typeof(value) === "string" && value.substring(0, 2) !== "0x") {
value = "0x" + value;
}
Expand Down Expand Up @@ -283,7 +289,7 @@ export function hexConcat(items: ReadonlyArray<BytesLike>): string {
return result;
}

export function hexValue(value: BytesLike | Hexable | number): string {
export function hexValue(value: BytesLike | Hexable | number | bigint): string {
const trimmed = hexStripZeros(hexlify(value, { hexPad: "left" }));
if (trimmed === "0x") { return "0x0"; }
return trimmed;
Expand Down

0 comments on commit 4e9abfd

Please sign in to comment.