1

I posted a couple of questions on this a few days ago and got some excellent replies JavaScript Typed Arrays - Different Views

My second question involved two views, 8-bit array and 32-bit array of a buffer. By placing 0, 1, 2, 3, in the 8-bit I got 50462976 in the 32-bit. As mentioned the reason for the 32-bit value was well explained.

I can achieve the same thing with the following code:

var buf = new ArrayBuffer(4);
var arr8 = new Int8Array(buf);
var arr32 = new Int32Array(buf);

for (var x = 0; x < buf.byteLength; x++) {
    arr8[x] =
        (x << 24) |
        (x << 16) |
        (x <<  8) |
         x;
}

console.log(arr8);      // [0, 1, 2, 3]
console.log(arr32);     // [50462976]

I can't find anything that explains the mechanics of this process. It seems to be saying that each arr8 element equals X bit-shifted 24 positions OR bit-shifted 16 positions OR bit-shifted 8 positions OR not bit-shifted.

That doesn't really make sense to me. I'd appreciate it if someone could shed some light on this. Thanks,

2 Answers 2

3

Basically, your buffer is like this:

00000000 00000001 00000010 00000011

When handled as an Int8Array, it reads each 8-bit group individually: 0, 1, 2, 3

When handled as an Int32Array, it reads 32-bit groups (ie. 4 8-bit groups) to get 50462976

Sign up to request clarification or add additional context in comments.

3 Comments

I can understand how I get 50462976 from the 32-bit array. What I don't get is the "|" sign. Since it means OR how does that work in the above context. That's why I was asking for the "mechanics" of the process.
It's a bitwise OR. In this case, because x is less than 8, it's actually exactly the same as +.
@NiettheDarkAbsol this saved my life...Thanks for this answer
2

The memory used by the buffer is interpreted as 8-bit bytes for the Int8Array and 32-bit words for the Int32Array. The ordering of the bytes in the 8-bit array is the same as the ordering of the bytes in the single 32-bit word in the other array because they're the same bytes. There are no "mechanics" involved; it's just two ways of looking at the same 4 bytes of memory.

You get the exact same effect in C if you allocate a four-byte array and then create an int pointer to the same location.

Furthermore, this expression here:

arr8[x] =
    (x << 24) |
    (x << 16) |
    (x <<  8) |
     x;

will do precisely the same thing as

arr8[x] = x;

You're shifting the value of x up into ranges that will be truncated away when the value is actually saved into the (8-bit) array element.

1 Comment

+1 for explaining that the bits after the first 8 are truncated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.