Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get usable unsigned 32 bit integer to work with?

Tags:

javascript

It exists in array form as Uint32Array ( signed version is Int32Array ), but I was told that once you access this value it becomes a normal JS number.

let number = (new Unit32Array(1)).fill(1)[0];

Where the variable number is implemented as a double and once you do a bitwise operation it is converted to a 32 bit signed integer.

I don't get the purpose of Unit32Array if you can actually use the un-signed representation in the array, i.e. once you access it, it pops out at a normal number?

function analyze () {
  // let test = 2147483647; // max 32 bit integer
  // let test = -2147483647; // min 32 bit integer
  for(let place = 0; place < 32; place++){
    let power2 = Math.pow(2, place);
    let bit = test & power2;
    console.log(place, bit)
  }
}
analyze();

/*
2^0 is 1 is 0x1
2^1 is 2
2^2 is 4
2^3 is 8
.
.

2^31 is 2147483648
2^32 is 4294967296
*/
like image 696
jennifer Avatar asked Sep 13 '25 21:09

jennifer


1 Answers

Use the triple right shift to use a number as unsigned. It essentially prevents sign-extension (and it works with Uint32Array).

 > var myNumber = -5;
-5
> myNumber >>> 0
4294967291
like image 137
Michael Bianconi Avatar answered Sep 15 '25 12:09

Michael Bianconi