質問

Does the JavaScript code

var n = 8; // or some arbitrary integer literal
n >> 1;

always denote "integer devision by 2 without remainer"? My concern is the endianess if the integer literal is larger than one byte.

The background of my question is the following:

I have an integer variable in the range from 0 to 2^32-1 that would fit into an uint32 if I had a typed programming language different than JS. I need to convert this into an Uint4Array with four elements in little endian order.

My current JavaScript approach is:

function uInt32ToLEByteArray( n ) {
  var byteArray = new Uint8Array(4);
    for( var i = 0; i < 4; i++ ) {
      byteArray[i] = n & 255;
      n >> 8;
    }
  return byteArray;
}

This code works in my browser, but I wonder if this would do everywhere. The principal idea is the fill the array by taking the LSB and divdiding by 256. But a real divions "/" would convert the variable into a floating point variable. So I use ">>8" but this actually assumes big endianness.

役に立ちましたか?

解決

The code you have given has absolutely no relevancy to endianess.

However, if you were to reinterpret the byte array in say uint32 array, then the result would be different depending on the endianess of the machine the browser runs on.

First, fix the bug in the code:

function uInt32ToLEByteArray(n) {
    var byteArray = new Uint8Array(4);
    for (var i = 0; i < 4; i++) {
        byteArray[i] = n & 255;
        n >>>= 8; //simply doing n >> 8 has no effect actually
    }
    return byteArray;
}

Then

var a = uInt32ToLEByteArray(0xFF)
console.log(a);
//always [255, 0, 0, 0]

var b = new Uint32Array(a.buffer);
console.log(b);
//[255] on little endian machines
//[4278190080] on big endian machines
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top