如何在 JavaScript 中 encode/decode Base36 中的 Uint8Array?
How to encode/decode a Uint8Array in Base36 in JavaScript?
我想对 Uint8Array(或 ArrayBuffer)to/from Base36 字符串中的字节进行编码和解码。 JavaScript 具有 toString and parseInt 函数,它们都支持 base36,但我不确定首先将 8 字节转换为 64 位浮点数是否正确。
在 JS 中,可以将 BigInt(任意长度的数字)编码为 Base36。然而另一个方向 not work.
我该怎么做?
我在这两个帖子的帮助下找到了解决方案: and How 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);
我想对 Uint8Array(或 ArrayBuffer)to/from Base36 字符串中的字节进行编码和解码。 JavaScript 具有 toString and parseInt 函数,它们都支持 base36,但我不确定首先将 8 字节转换为 64 位浮点数是否正确。
在 JS 中,可以将 BigInt(任意长度的数字)编码为 Base36。然而另一个方向 not work.
我该怎么做?
我在这两个帖子的帮助下找到了解决方案:
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);