【问题标题】:Convert Binary ArrayBuffer/TypedArray Data to Hex String将二进制 ArrayBuffer/TypedArray 数据转换为十六进制字符串
【发布时间】:2020-04-05 03:12:57
【问题描述】:
我想从我正在阅读的二进制文件中获取校验和字符串。校验和由 Uint32 值表示,但如何将其转换为文本?整数值为1648231196,对应的文本应为“1c033e62”(通过元数据实用程序知道)。请注意,我不是在尝试计算校验和,只是尝试将表示校验和的字节转换为字符串。
【问题讨论】:
标签:
javascript
binary-data
arraybuffer
typed-arrays
【解决方案1】:
您可以通过两种方式读取字节,Big-Endian and Little-Endian。
嗯,您提供的“校验和”是 Little-Endian 中的“十六进制”。因此,我们可以创建一个缓冲区并设置指定 Little-Endian 表示的数字。
// Create the Buffer (Uint32 = 4 bytes)
const buffer = new ArrayBuffer(4);
// Create the view to set and read the bytes
const view = new DataView(buffer);
// Set the Uint32 value using the Big-Endian (depends of the type you get), the default is Big-Endian
view.setUint32(0, 1648231196, false);
// Read the uint32 as Little-Endian Convert to hex string
const ans = view.getUint32(0, true).toString(16);
// ans: 1c033e62
始终在DataView.setUint32 中指定第三个参数,在DataView.getUint32 中指定第二个参数。这定义了“Endian”的格式。如果不设置,可能会得到意想不到的结果。