I would like to get a checksum string from a binary file I'm reading. The checksum is represented by a Uint32 value, but how do I convert it to text? The integer value is 1648231196 and the corresponding text should be "1c033e62" (known via a metadata util). Note, I am not trying to calculate a checksum, only trying to convert bytes representing the checksum to a string.
-
1Have you already reviewed the following: stackoverflow.com/questions/9854166/…PM 77-1– PM 77-12019-12-11 19:19:37 +00:00Commented Dec 11, 2019 at 19:19
-
Thanks, but wrong language :)Justin– Justin2020-11-03 19:14:59 +00:00Commented Nov 3, 2020 at 19:14
Add a comment
|
1 Answer
There are two ways who you can read the bytes, Big-Endian and Little-Endian.
Well, the "checksum" who you provide is a "hex" in Little-Endian. So we can create a buffer and set the number specifying the Little-Endian representation.
// 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
Always specify the 3rd parameter in DataView.setUint32 and the 2nd in DataView.getUint32. This defines the format of the "Endian". If you don't set it you can get unexpected results.