简体   繁体   English

JavaScript中的整数除法和位移

[英]Integer division and bit shift in JavaScript

Does the JavaScript code 是JavaScript代码吗?

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

always denote "integer devision by 2 without remainer"? 总是表示“没有剩余的2整数分割”? My concern is the endianess if the integer literal is larger than one byte. 如果整数文字大于一个字节,我关心的是endianess。

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. 我有一个0到2 ^ 32-1范围内的整数变量,如果我有一个不同于JS的类型化编程语言,它将适合uint32。 I need to convert this into an Uint4Array with four elements in little endian order. 我需要将它转换为Uint4Array,其中包含四个以小端顺序排列的元素。

My current JavaScript approach is: 我目前的JavaScript方法是:

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. 主要思想是通过取LSB并将divdiding 256来填充数组。但是真正的divions“/”会将变量转换为浮点变量。 So I use ">>8" but this actually assumes big endianness. 所以我使用“>> 8”但这实际上假设了大字节。

The code you have given has absolutely no relevancy to endianess. 您提供的代码绝对与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. 但是,如果你要重新解释说uint32数组中的字节数组,那么结果会有所不同,具体取决于浏览器运行的机器的字节顺序。

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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM