Search code examples
javascriptbinaryarraybuffer

ArrayBuffer's Binary clarification


https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView/setInt8

Just want to clarify something here, when this article says:

The setInt8() method stores a signed 8-bit integer (byte) value at the specified byte offset from the start of the DataView.<<

and then you execute this code

var buffer = new ArrayBuffer(8);
var dataview = new DataView(buffer);
dataview.setInt8(1, 3);
dataview.setInt8(3, -3);

buffer is actually:

[
00000000,
00000011,
00000000,
10000011,
00000000,
00000000,
00000000,
00000000
]

with the highest number possible being 127?

I think I've confirmed that with

dataview.setInt8(1,128);
dataview.getInt8(1); // -127

However... I'm then confused as to why it reverts back...

dataview.setInt8(1, 255);
dataview.getInt8(1); // -1

dataview.setInt8(1, 257);
dataview.getInt8(1); // 1

Shouldn't I be getting an error with dataview.setInt8(1,257) since 256 is beyond the scope of the 8-bit integer? I'm just trying to confirm that buffer is actually the array of binary I listed above... so this would make a difference if that 8-bit integer was converted to a 16 bit integer... thanks!


Solution

  • If you try this:

    dataview.setInt8(1,1);
    dataview.getInt16(1); // 256
    dataview.setInt8(1,257);
    dataview.getInt16(1); // 256
    

    you can confirm that setInt8 is only writing to one byte of the buffer, even when given an input value that's more than 8 bits. So you're safe there.

    What's odd is that .setInt8() and .setUint8() appear to be the same function (on Chrome, the only browser I tried). Neither .setInt8(1,255) nor .setUint8(1,-1) return an error, and .setInt8(1,-1) and .setUint8(1,-1) have identical effects.

    Additionally, you asked 'with the highest number possible being 127?'. Yes, IF you're reading the buffer with getInt8(). Reading it with getUint8() or getInt16() or etc could return a value higher than 127. Unlike the set functions, the get functions appear to (correctly) behave differently with regards to signing.

    Starting with an empty buffer, if you execute:

    dataview.setInt8(1,3);
    dataview.setInt8(3,3);
    

    the buffer will contain:

    00000000 00000011 00000000 11111101
    

    You can verify this by trying:

    dataview.getInt32(0); // 196861 = 110000000011111101
    

    Negative numbers are being represented via Two's Complement in the buffer