【问题标题】:How to encode/decode a Uint8Array in Base36 in JavaScript?如何在 JavaScript 中对 Base36 中的 Uint8Array 进行编码/解码?
【发布时间】:2021-08-16 20:19:13
【问题描述】:

我想对来自 Uint8Array(或 ArrayBuffer)的字节与 Base36 中的字符串进行编码和解码。 JavaScript 有 toStringparseInt 函数,它们都支持 base36,但我不确定首先将 8 字节转换为 64 位浮点是否正确。

在 JS 中,可以在 Base36 中编码一个 BigInt(任意长度的数字)。但是另一个方向是not work

我该怎么做?

【问题讨论】:

  • 这能回答你的问题吗? How do I convert a float to base36 in Python?
  • @DhanaD 在 Base36 中编码单个浮点数在 javascript 中很容易。我的问题是我是否应该首先将我的字节数组转换为浮点数组,然后将每个浮点数转换为 Base36。我认为我无法解码字符串,因为结果的长度不同。
  • @DhanaD。请不要尝试将问题作为另一种语言的重复问题来结束。见this meta question for the discussion

标签: javascript encoding base36


【解决方案1】:

我在这两个帖子的帮助下找到了解决方案:Why JavaScript base-36 conversion appears to be ambiguousHow to go between JS BigInts and TypedArrays

function bigIntToBase36(num){
    return num.toString(36);
}

function base36ToBigInt(str){
    return [...str].reduce((acc,curr) => BigInt(parseInt(curr, 36)) + BigInt(36) * acc, 0n);
}

function bigIntToBuffer(bn) {
    let hex = BigInt(bn).toString(16);
    if (hex.length % 2) { hex = '0' + hex; }

    const len = hex.length / 2;
    const u8 = new Uint8Array(len);

    let i = 0;
    let j = 0;
    while (i < len) {
        u8[i] = parseInt(hex.slice(j, j+2), 16);
        i += 1;
        j += 2;
    }

    return u8;
}

function bufferToBigInt(buf) {
    const hex = [];
    const u8 = Uint8Array.from(buf);

    u8.forEach(function (i) {
        var h = i.toString(16);
        if (h.length % 2) { h = '0' + h; }
        hex.push(h);
    });

    return BigInt('0x' + hex.join(''));
}

const t1 = new Uint8Array([123, 51, 234, 234, 24, 124, 2, 125, 34, 255]);
console.log(t1);
const t2 = bigIntToBase36(bufferToBigInt(t1));
console.log(t2);
console.log(t2.length)
const t3 = bigIntToBuffer(base36ToBigInt(t2));
console.log(t3);

【讨论】:

    猜你喜欢
    • 2011-03-14
    • 2019-08-18
    • 2016-05-28
    • 2012-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-08
    相关资源
    最近更新 更多