【问题标题】:How do I unpack a data from a binary string in Node.js?如何从 Node.js 中的二进制字符串中解压缩数据?
【发布时间】: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


    【解决方案1】:

    查看这个 sn-p:

     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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-06
      • 2016-11-01
      • 2020-11-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多