NodeJS 如何将字符串转换为Cairo毛毡(字段元素)?

ruoxqz4g  于 2023-01-04  发布在  Node.js
关注(0)|答案(2)|浏览(98)

开罗要求所有数据都是有感觉的。https://www.cairo-lang.org/docs/how_cairo_works/cairo_intro.html#field-elements
如何在JavaScript中将字符串转换为felt?

inb24sb2

inb24sb21#

下面介绍如何将字符串转换为felt数组。建议使用felt数组,因为普通的felt只能包含31个字符。如果31个字符对你来说足够了,那么你可以只使用数组的第一个元素作为结果:https://github.com/immutable/imx-starknet/blob/main/tests/utils/starknetUtils.ts#L60

/**
 * 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(),
    ""
  );
}
7kqas0il

7kqas0il2#

要从浏览器中获取字符串,这是一种享受,

const felt = 113741024818209;

const feltToString = felt => felt
  // To hex
  .toString(16)
  // Split into 2 chars
  .match(/.{2}/g)
  // Get char from code
  .map( c => String.fromCharCode(parseInt( c, 16 ) ) )
  // Join to a string
  .join('');

相关问题