Left shift (bit-wise operation) in Java and JavaScript

I found this task on LeetCode, and found a strange thing in bit-wise operation in JavaScript. So here’s a record of it.

The task was:

Reverse bits of a given 32 bits unsigned integer.

Input: 00000010100101000001111010011100
Output: 00111001011110000010100101000000

Then, I wrote the following code.

let result = 0;
for(let i = 0; i < 32; i++) {
  // passing the smallest bit of n to result, and update n

  if(i < 31) result <<= 1; // This look fine, doesn't it?
return result;

However, this didn’t work if the largest bit in `result` was 1. Apparently, the result was treated as a signed integer.

A funny thing I found is that, if I converted the code in Java, the solution worked.

It turned out that using the left shift operation (<<) turns a number in JavaScript, which is supposed to be 64 bits floating-point number, into 32 bits signed integer.

JavaScript stores numbers as 64 bits floating point numbers, but all bitwise operations are performed on 32 bits binary numbers.

Before a bitwise operation is performed, JavaScript converts numbers to 32 bits signed integers.


The task is “Reverse bits of a given 32 bits unsigned integer”, so there must not be a conversion from unsigned to signed integer. To keep the input an unsigned integer, I could use…

result *= 2; // Move all the bits towards left

(In Java, int is, by default, a 32-bit signed integer. As of Java 8, it can be unsigned. << is defined as the “signed left shift operator”.)

Leave a Reply

Your email address will not be published. Required fields are marked *