Calebmer
Calebmer

Reputation: 2860

Why do Uint8Array and Uint32Array have different binary representations when I look at their elements?

I have the following code:

const uint8 = new Uint8Array(buffer);

let uint8String = "";
for (const n of uint8) uint8String += n.toString(2).padStart(8, "0");
console.log(uint8String);

const uint32 = new Uint32Array(uint8.buffer);

let uint32String = "";
for (const n of uint32) uint32String += n.toString(2).padStart(32, "0");
console.log(uint32String);

Which logs:

Which are different binary strings. What’s the reason for the difference?

Upvotes: 0

Views: 251

Answers (1)

Robert Harvey
Robert Harvey

Reputation: 180808

Because Javascript on an Intel machine is Little Endian.

Consider the first four bytes of your two arrays:

10111001 11100001 11000100 00100001 <-- Four unsigned bytes

00100001 11000100 11100001 10111001 <-- One unsigned int

Notice that the bytes are swapped end-to-end? That's because the byte order in the first array is in the order in which you placed the characters, but the second array stores each unsigned int as Little Endian, which means the Least Significant Byte (LSB) is stored at the smallest memory location.

Further Reading
Endianness on Wikipedia

Upvotes: 2

Related Questions