如何从 Node.js 中的二进制字符串中解压数据?
How do I unpack a data from a binary string in Node.js?
在 PHP 中,您可以按如下方式执行此操作:
$raw_data = base64_decode("1Xr5WEtvrApEByOh4GtDb1nDtls");
$unpacked = unpack('Vx/Vy', $raw_data);
/* output:
array(2) {
["x"]=>
int(1492744917)
["y"]=>
int(179072843)
}
*/
如何在 Node.js 中获得相同的结果?
到目前为止,我试过这个:
const base64URLDecode = (data) => {
let buffer
data = data.replace(/-/g, '+').replace(/_/g, '/')
while (data.length % 4) {
data += '='
}
if (data instanceof Buffer) {
buffer = data
} else {
buffer = Buffer.from(data.toString(), 'binary')
}
return buffer.toString('base64')
}
const byteToUINT8 = (bytes) => {
const byteLength = bytes.length
const uint8Arr = new Uint8Array(byteLength)
return uint8Arr.map((char, key) => bytes.charCodeAt(key))
}
const unpack = (binString) => {
const byteChars = base64URLDecode(binString)
const uint8Arr = byteToUINT8(byteChars)
const uint32Arr = new Uint32Array(uint8Arr.buffer)
return uint32Arr
}
unpack('1Xr5WEtvrApEByOh4GtDb1nDtls') // output: [1180980814, 2036880973, ...]
但是,与 PHP 的 unpack
相比,这给了我一个完全不匹配的结果。我做错了什么?
查看此代码段:
const buf = Buffer.from("1Xr5WEtvrApEByOh4GtDb1nDtls", 'base64')
const uint32array = new Uint32Array(buf.buffer, buf.byteOffset, buf.length / Uint32Array.BYTES_PER_ELEMENT)
// Variable uint32array presents:
// Uint32Array(5) [
// 1492744917,
// ... ]
关于 Nodejs TypedArray 的文档在这里:Nodejs Buffer
在 PHP 中,您可以按如下方式执行此操作:
$raw_data = base64_decode("1Xr5WEtvrApEByOh4GtDb1nDtls");
$unpacked = unpack('Vx/Vy', $raw_data);
/* output:
array(2) {
["x"]=>
int(1492744917)
["y"]=>
int(179072843)
}
*/
如何在 Node.js 中获得相同的结果?
到目前为止,我试过这个:
const base64URLDecode = (data) => {
let buffer
data = data.replace(/-/g, '+').replace(/_/g, '/')
while (data.length % 4) {
data += '='
}
if (data instanceof Buffer) {
buffer = data
} else {
buffer = Buffer.from(data.toString(), 'binary')
}
return buffer.toString('base64')
}
const byteToUINT8 = (bytes) => {
const byteLength = bytes.length
const uint8Arr = new Uint8Array(byteLength)
return uint8Arr.map((char, key) => bytes.charCodeAt(key))
}
const unpack = (binString) => {
const byteChars = base64URLDecode(binString)
const uint8Arr = byteToUINT8(byteChars)
const uint32Arr = new Uint32Array(uint8Arr.buffer)
return uint32Arr
}
unpack('1Xr5WEtvrApEByOh4GtDb1nDtls') // output: [1180980814, 2036880973, ...]
但是,与 PHP 的 unpack
相比,这给了我一个完全不匹配的结果。我做错了什么?
查看此代码段:
const buf = Buffer.from("1Xr5WEtvrApEByOh4GtDb1nDtls", 'base64')
const uint32array = new Uint32Array(buf.buffer, buf.byteOffset, buf.length / Uint32Array.BYTES_PER_ELEMENT)
// Variable uint32array presents:
// Uint32Array(5) [
// 1492744917,
// ... ]
关于 Nodejs TypedArray 的文档在这里:Nodejs Buffer