/**
* Splits a string into an array of short strings (felts). A Cairo short string (felt) represents up to 31 utf-8 characters.
* @param {string} str - The string to convert
* @returns {bigint[]} - The string converted as an array of short strings as felts
*/
export function strToFeltArr(str: string): BigInt[] {
const size = Math.ceil(str.length / 31);
const arr = Array(size);
let offset = 0;
for (let i = 0; i < size; i++) {
const substr = str.substring(offset, offset + 31).split("");
const ss = substr.reduce(
(memo, c) => memo + c.charCodeAt(0).toString(16),
""
);
arr[i] = BigInt("0x" + ss);
offset += 31;
}
return arr;
}
反之亦然
* Converts an array of utf-8 numerical short strings into a readable string
* @param {bigint[]} felts - The array of encoded short strings
* @returns {string} - The readable string
*/
export function feltArrToStr(felts: bigint[]): string {
return felts.reduce(
(memo, felt) => memo + Buffer.from(felt.toString(16), "hex").toString(),
""
);
}
2条答案
按热度按时间inb24sb21#
下面介绍如何将字符串转换为felt数组。建议使用felt数组,因为普通的felt只能包含31个字符。如果31个字符对你来说足够了,那么你可以只使用数组的第一个元素作为结果:https://github.com/immutable/imx-starknet/blob/main/tests/utils/starknetUtils.ts#L60
反之亦然
7kqas0il2#
要从浏览器中获取字符串,这是一种享受,