How to store a 32-bit integer in an arraybuffer?

Viewed 1422

I seem to not be understanding the Uint32Array. According to what I've read about the Uint8Array I could just feed it a number inside an array (Uint8Array([16]) or Uint8Array([96,56])) and the results are exactly that. However, when I try the same thing for a larger number like Uint32Array([21640]), it seems to truncate it. Where 21640 should equal 5488 in hex, I only get 88. How does this actually work?

Edit: Elaborations

I am also attempting to concatenate several ArrayBuffers together. If I'm not mistaken readAsArrayBuffer produces an Uint8Array, and I am trying to append to that some 32-bit numbers using https://gist.github.com/72lions/4528834

There is so much information and examples on Uint8Array and what little there was on Uint32Array makes me think that one of these 32 would store a value as if it was 4 of the 8.

2 Answers

The largest value of an unsigned 8 bit number is 255. Larger numbers will be truncated or rolled over depending on the os/cpu. If you want to convert a 32 bit numbers in an 8 bit array try something like this.

var number = 21640;
var byte1 = 0xff & number;
var byte2 = 0xff & (number >> 8);
var byte3 = 0xff & (number >> 16);
var byte4 = 0xff & (number >> 24);

var arr1 = Uint8Array([byte1,byte2,byte3,byte4]);

Just reverse the order of the bytes when you create the array depending on if you want little or big endian.

Here is a working example showing 5488 in console

    var bigNumber = new Uint32Array([21640]);
    console.log(bigNumber[0].toString(16));

Since you've added more to the question. If you wanted to convert

var byte1 = 0x88;
var byte2 = 0x54;
var byte3 = 0;
var byte4 = 0;

var bigValue = (byte4 << 24) | (byte3 << 16) | (byte2 << 8) | (byte1);

console.log(bigValue);

Although you will need to factor in Endianness

Related