首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在JavaScript中对Base36中的Uint8Array进行编码/解码?

如何在JavaScript中对Base36中的Uint8Array进行编码/解码?
EN

Stack Overflow用户
提问于 2021-08-15 14:10:03
回答 1查看 136关注 0票数 0

我想在Base36中对Uint8Array (或ArrayBuffer)中的字节进行编码和解码,并将其转换为字符串。JavaScript有toStringparseInt函数,这两个函数都支持base36,但我不确定首先将8字节转换为64位浮点是不是正确的想法。

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

我该怎么做呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-08-16 12:19:13

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

代码语言:javascript
复制
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);

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68792312

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档