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

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

nmhanq 回答:将Binary ArrayBuffer / TypedArray数据转换为十六进制字符串

有两种读取字节的方法,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中指定第二个参数。这定义了“字节序”的格式。如果不设置它,则会得到意想不到的结果。

本文链接:https://www.f2er.com/2939089.html

大家都在问