Reversing the bits of a decimal number and returning new decimal number in JavaScript

We are required to write a JavaScript function that takes in a decimal number, converts it into binary and reverses its bits (1 to 0 and 0 to 1) and returns the decimal equivalent of the new binary thus formed.

Problem

Given a decimal number, we need to:

  1. Convert the decimal number to binary
  2. Flip each bit (0 becomes 1, 1 becomes 0)
  3. Convert the resulting binary back to decimal

Example

Let's implement the function to reverse bits and convert back to decimal:

const num = 45657;
const reverseBitsAndConvert = (num = 1) => {
    const binary = num.toString(2);
    let newBinary = '';
    for(let i = 0; i < binary.length; i++){
        const bit = binary[i];
        newBinary += bit === '1' ? '0' : '1';
    };
    const decimal = parseInt(newBinary, 2);
    return decimal;
};
console.log(reverseBitsAndConvert(num));

Output

19878

How It Works

Let's trace through the example with number 45657:

const num = 45657;
console.log("Original number:", num);
console.log("Binary representation:", num.toString(2));

// Step-by-step bit flipping
const binary = num.toString(2);
let flipped = '';
for(let i = 0; i < binary.length; i++){
    const originalBit = binary[i];
    const flippedBit = originalBit === '1' ? '0' : '1';
    flipped += flippedBit;
    console.log(`Position ${i}: ${originalBit} -> ${flippedBit}`);
}

console.log("Flipped binary:", flipped);
console.log("Final decimal:", parseInt(flipped, 2));
Original number: 45657
Binary representation: 1011001001101001
Position 0: 1 -> 0
Position 1: 0 -> 1
Position 2: 1 -> 0
Position 3: 1 -> 0
Position 4: 0 -> 1
Position 5: 0 -> 1
Position 6: 1 -> 0
Position 7: 0 -> 1
Position 8: 0 -> 1
Position 9: 1 -> 0
Position 10: 1 -> 0
Position 11: 0 -> 1
Position 12: 1 -> 0
Position 13: 0 -> 1
Position 14: 0 -> 1
Position 15: 1 -> 0
Flipped binary: 0100110110010110
Final decimal: 19878

Alternative Implementation

Here's a more concise version using array methods:

const reverseBitsAndConvertAlt = (num) => {
    return parseInt(
        num.toString(2)
           .split('')
           .map(bit => bit === '1' ? '0' : '1')
           .join(''),
        2
    );
};

console.log(reverseBitsAndConvertAlt(45657));
console.log(reverseBitsAndConvertAlt(10));
console.log(reverseBitsAndConvertAlt(255));
19878
5
0

Conclusion

This bit manipulation technique converts a decimal to binary, flips each bit, and converts back to decimal. The key is using toString(2) for binary conversion and parseInt(binary, 2) for decimal conversion.

Updated on: 2026-03-15T23:19:00+05:30

338 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements