# JavaScript 32 bit integer unsigned operation example

- 2020-03-30 00:47:37
- OfStack

In JavaScript, all integer numeric variables are signed integers by default. What does that mean?

A signed integer USES 31 bits for the value of an integer, 32 bits for the sign of an integer, 0 for a positive number, and 1 for a negative number.

The values range from minus 2^31- 2^31-1 which is minus 2147483648 to 2147483647.

When JavaScript performs a bit operation, it takes a 32-bit signed integer, which means that the result of its conversion is also a 32-bit signed integer. Sometimes, we do the shift will be unexpected results, the following is the C language and JS comparison.

The C language

JavaScript

As you can see, JavaScript USES a signed integer when performing bit operations, so we get a different result. What's the solution?

We can convert signed Numbers in JavaScript to unsigned Numbers. Just do it > > > The 0 shift operation is fine.

It is best not to use > > It is recommended to use > > > Because the leftmost bit will be resolved into a sign bit, when the number overflows, it will be resolved into a negative number.

A signed integer USES 31 bits for the value of an integer, 32 bits for the sign of an integer, 0 for a positive number, and 1 for a negative number.

The values range from minus 2^31- 2^31-1 which is minus 2147483648 to 2147483647.

When JavaScript performs a bit operation, it takes a 32-bit signed integer, which means that the result of its conversion is also a 32-bit signed integer. Sometimes, we do the shift will be unexpected results, the following is the C language and JS comparison.

The C language

```
unsigned int a = 3774191835u;
unsigned int b = a >> 2;
```

JavaScript

```
var a = 3774191835;
var b = a >> 2;
```

As you can see, JavaScript USES a signed integer when performing bit operations, so we get a different result. What's the solution?

We can convert signed Numbers in JavaScript to unsigned Numbers. Just do it > > > The 0 shift operation is fine.

It is best not to use > > It is recommended to use > > > Because the leftmost bit will be resolved into a sign bit, when the number overflows, it will be resolved into a negative number.