Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitwise operations on 32-bit unsigned ints?

JavaScript converts operands to 32-bit signed ints before doing bitwise operations. It also does the operation with 32-bit signed ints, meaning that the result is a 32-bit signed int.

Because I'd like to do bitwise operations with 32-bit unsigned ints, I'm wondering if there is a way to use JavaScript's mangled result to find out the intended result.

To demonstrate my idea, for example, in C, which is the reference as to what I'd like,

unsigned int a = 3774191835u; unsigned int b = a >> 2; /* b == 943547958 */ 

In JavaScript,

 var a = 3774191835;  var b = a >> 2;  /* b == -130193866 */ 

Let's try this with a different operation. In C,

unsigned int a = 1986735448u; unsigned int b = a << 1; /* b == 3973470896 */ 

In JavaScript,

 var a = 1986735448;  var b = a << 1;  /* b == -321496400 */ 

Now that JavaScript has evaluated my bitwise operation with the operand as an signed int, we of course, get a different result to what we would in C, where we can properly do bitwise operations on unsigned ints.

I know it's possible, but I'm unsure of a way that I can, essentially, turn JavaScript's result into the intended result.


Zero-fill right shift the result by zero works for the second case only, but not the first.

 var a = 3774191835;  var b = (a >> 2) >>> 0;  /* b == 4164773430 */   var a = 1986735448;  var b = (a << 1) >>> 0;  /* b == 3973470896 */ 
like image 589
Delan Azabani Avatar asked Jul 23 '11 03:07

Delan Azabani


People also ask

How many bits are in an unsigned int?

An unsigned integer is a 32-bit datum that encodes a nonnegative integer in the range [0 to 4294967295].

What is the largest number represented by a 32-bit unsigned integer?

A 32-bit signed integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). A 32-bit unsigned integer. It has a minimum value of 0 and a maximum value of 4,294,967,295 (inclusive).

How can bitwise operator identify odd number?

The idea is to check whether the last bit of the number is set or not. If the last bit is set then the number is odd, otherwise even. As we know bitwise XOR Operation of the Number by 1 increment the value of the number by 1 if the number is even otherwise it decrements the value of the number by 1 if the value is odd.


1 Answers

You only have to follow these rules:

  1. always end bit wise ops with >>> 0 so the result gets interpreted as unsigned.
  2. don't use >>. If the left-most bit is 1 it will try to preseve the sign and thus will introduce 1's to the left. Always use >>>.

Examples:

C:  (3774191835 >> 2) | 2147483648 js: (3774191835 >>> 2 | 2147483648) >>> 0  C:  1986735448 << 1 js: (1986735448 << 1) >>> 0  C:  3774191835 & 4294967295 js: (3774191835 & 4294967295) >>> 0 

Only if the last op is >>>, >>> 0 is not necessary.

like image 113
Ernesto Badillo Avatar answered Oct 06 '22 02:10

Ernesto Badillo