将二进制 ArrayBuffer/TypedArray 数据转换为十六进制字符串

Convert Binary ArrayBuffer/TypedArray Data to Hex String

我想从正在读取的二进制文件中获取校验和字符串。校验和由 Uint32 值表示,但如何将其转换为文本?整数值为 1648231196,对应的文本应为“1c033e62”(通过元数据实用程序获知)。请注意,我不是要计算校验和,只是尝试将表示校验和的字节转换为字符串。

有两种读取字节的方法,Big-Endian and Little-Endian

好吧,您提供的 "checksum" 是 Little-Endian 中的 "hex"。所以我们可以创建一个缓冲区并设置指定 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 and the 2nd in DataView.getUint32 中指定第 3 个参数。这定义了 "Endian" 的格式。如果你不设置它,你会得到意想不到的结果。