【发布时间】:2021-07-28 16:12:27
【问题描述】:
在 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 相比,这给了我一个完全不匹配的结果。我做错了什么?
【问题讨论】:
标签: javascript php node.js binary buffer