Search code examples
javascriptmemoryarraybuffer

I am testing ArrayBuffer and wonder why the result looks like this:


Hi I am a beginner programmer who is studying JavaScript. When I look at the source, I create a view with a DataView (buffer) and put the value into position 0 with setUint32. Why does not the value 536870912 change to 32 when I load the buffer again with Uint32Array?

var buffer = new ArrayBuffer(76);
var view = new DataView(buffer);

var value = 20000000;

// set value 536807912
view.setUint32(0, parseInt(value, 16));

// [17/05/2019 10:00:20.149] [LOG]    getUint32 536870912
console.log('getUint32 ' + view.getUint32(0));

var test = new Uint32Array(buffer);

/* [17/05/2019 10:00:20.150] [LOG]    Uint32Array [ 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] */
console.log(test);

Solution

  • The reason you see 32 using Uint32Array is due to Endianness. When using a DataView, the setUint32 and getUint32 functions have an additional parameter littleEndian and when left out it defaults to big-endian. Then, using a Uint32Array, it will use your system's endianness which in this case is little-endian.

    So in the Uint32Array case you are setting the value using big-endian, then retrieving it using little-endian resulting in the value of 32.

    To illustrate this, here are the two values using the different byte orders:

    536870912 =
    Little-endian:  00 00 00 20
    Big-endian: 20 00 00 00
    
    32 =
    Little-endian:  20 00 00 00
    Big-endian: 00 00 00 20