albertonline· portal
blind75

Reversing Bits of an Integer

Dec 26, 2023 · A detailed explanation of how to reverse the bits of a 32-bit unsigned integer using bitwise operations in JavaScript.

The "Reverse Bits" problem is a classic bit manipulation challenge that involves reversing the bits of a given 32-bit unsigned integer.

Problem Statement

Given a 32-bit unsigned integer n, the goal is to reverse its bits and return the result.

Example

  • Input: n = 43261596 (binary representation: 00000010100101000001111010011100)
  • Output: 964176192 (binary representation: 00111001011110000010100101000000)

JavaScript Solution

Here's an efficient way to solve this problem in JavaScript:

function reverseBits(n) {
  let result = 0;
  for (let i = 0; i < 32; i++) {
    result = (result << 1) | (n & 1);
    n >>>= 1;
  }
  return result >>> 0; // Ensure unsigned 32-bit integer
}

Breaking Down the Solution

  • Initialization: Start with result set to 0. This variable will hold the reversed bits.

  • Iterative Bitwise Operations: For 32 iterations (each iteration represents a bit in the 32-bit integer):

    • Left-shift result: Shift result left by one bit (result << 1). This operation makes space for adding the new bit at the least significant position.

    • Add Bit to result: Use bitwise OR (|) to add the rightmost bit of n to result. The expression n & 1 isolates the least significant bit of n, which is then added to result.

    • Right-shift n: Shift n right by one bit (n >>>= 1). This operation moves all bits of n to the right by one position, bringing the next bit in line to be processed.

  • Return Unsigned Integer: The expression result >>> 0 converts result to an unsigned 32-bit integer. This step ensures that the final returned value is in the correct format, respecting the constraints of the problem.

Conclusion

Reversing the bits of an integer is a valuable exercise in bit manipulation. It demonstrates how bitwise operations can be used to precisely control and manipulate individual bits within integers. This problem is not only frequently asked in technical interviews but also plays a crucial role in areas like low-level computing and digital signal processing, where bit-level manipulation is common.

Comments (0)

Stub comments live in your browser only (localStorage). No server round-trip yet.

No comments yet. Be the first.