3

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.

phuzi
  • 12,078
  • 3
  • 26
  • 50
Edward
  • 495
  • 1
  • 6
  • 20
  • "It seems"? It *is*, because you can't fit 32 bits into 8. You need to break it up. – Dave Newton Oct 08 '19 at 14:04
  • @DaveNewton Any suggestions on how to break it up into `Uint8Array(4)` so it becomes `88 54 00 00`? – Edward Oct 08 '19 at 14:13
  • It is working fine. Must be something wrong with your hex printing routine only handling byte. Without showing any code it is not possible to be certain that this is the problem. – John Oct 08 '19 at 14:18

2 Answers2

2

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.

Skye MacMaster
  • 894
  • 1
  • 10
  • 19
0

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

John
  • 3,716
  • 2
  • 19
  • 21