Search code examples
javascriptarraybuffer

UInt16Array not working as expected (wrong order)


I have some binary data in a file im reading (Hex):

00 00 00 18 66 74 79 70

I read the file and convert it to an arrayBuffer and both Uint8Array and Uint16Array.

const arrayBuffer = await selectedFile.arrayBuffer()
  
const uint8Array  = new Uint8Array(arrayBuffer)
const uint16Array = new UInt16Array(arrayBuffer)  

The content of Uint8Array is as expected:

   Decimal        Hex

0: 0              0
1: 0              0
2: 0              0
3: 24             18   
4: 102            66
5: 116            74
6: 121            79
7: 112            70

But in the uint16Array the two bytes are flipped.

   Decimal        Hex          What I expected as Hex

0: 0              0            0
1: 6144           18 00        00 18
2: 29798          74 66        66 74
3: 28793          70 79        79 70

Why are the two bytes flipped? What can I do to get the right order, if e.g. I need to search 0x6674.


Solution

  • The endianness of the file (of the data format) is a different one than that of your processor.

    If you care about endianness (and you do, if you read or write files meant to be used on different platforms), don't use a Uint16Array that always uses the platform byte order, use a DataView instead and call the getUint16 method for each index.