Skip to content

Commit

Permalink
add stringToNumber to utils;ts
Browse files Browse the repository at this point in the history
  • Loading branch information
remicolin committed Aug 7, 2024
1 parent b427e23 commit d365e5a
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions common/src/utils/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -363,3 +363,30 @@ export function BigintToArray(n: number, k: number, x: bigint) {
}
return ret;
}


/**
* Converts a string of maximum 30 characters to a single BigInt.
* Each byte is represented by three digits in the resulting BigInt.
* @param str The input string (max 30 characters)
* @returns A BigInt representing the concatenated byte values
*/
export function stringToNumber(str: string): bigint {
if (str.length > 30) {
throw new Error("Input string must not exceed 30 characters");
}
return BigInt('1' + Array.from(str)
.map(char => char.charCodeAt(0).toString().padStart(3, '0'))
.join(''));
}

/**
* Converts a BigInt (representing concatenated byte values) back to a string.
* @param num The input BigInt
* @returns The reconstructed string
*/
export function numberToString(num: bigint): string {
const str = num.toString().slice(1); // Remove leading '1'
const charCodes = str.match(/.{1,3}/g) || [];
return String.fromCharCode(...charCodes.map(code => parseInt(code, 10)));
}

0 comments on commit d365e5a

Please sign in to comment.