Search code examples
javascriptbinary-dataarraybuffertyped-arrays

Convert Binary ArrayBuffer/TypedArray Data to Hex String


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.


Solution

  • 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.