JavaScript integer division and bit shift

Is JavaScript code

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

always mean "integer allotment of 2 with no remainder"? My concern is endianess if the integer literal is more than one byte.

The background of my question is this:

I have an integer variable ranging from 0 to 2 ^ 32-1 that will fit in uint32 if I had a typed programming language other than JS. I need to convert this to a Uint4Array with four elements in a small trailing order.

My current JavaScript approach:

 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 it will do it everywhere. The main idea is to fill the array by taking LSB and dividing it by 256. But real divs "/" convert the variable to a floating point variable. Therefore, I use "β†’ 8", but in fact it assumes greater reliability.

+4
source share
1 answer

The code you provided has absolutely nothing to do with endianess.

However, if you want to reinterpret the byte array in the uint32 array, then the result will differ depending on the finiteness of the machine on which the browser is running.

First fix the error 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 
+1
source

Source: https://habr.com/ru/post/1497498/


All Articles