w3resource

JavaScript: Reverse the order of the bits in a given integer

JavaScript Basic: Exercise-127 with Solution

Write a JavaScript program to reverse the order of bits in a integer.

14 -> 00001110 -> 01110000 -> 112
56 -> 00111000 -> 00011100 -> 28
234 -> 11101010 -> 01010111 -> 87

Visual Presentation:

JavaScript: Reverse the order of the bits in a given integer.

Sample Solution:

JavaScript Code:

// Function to mirror bits of a given number
function mirror_bits(n) {
    // Convert number to binary and split into array of bits
    let t = n.toString(2).split("");
	
    // Get the length of the binary string
    let str_len = t.length;

    // Add leading zeroes to make the length of the binary string 8
    for (let i = 0; i < 8 - str_len; i++) {
        t.unshift("0");
    }

    // Reverse the bits and convert the binary string back to a number
    return parseInt(t.reverse().join(""), 2);
}

// Test cases with comments showing the step-by-step process
// 14 -> 00001110 -> 01110000 -> 112
console.log(mirror_bits(14));
// 56 -> 00111000 -> 00011100 -> 28
console.log(mirror_bits(56));
// 234 -> 11101010 -> 01010111 -> 87
console.log(mirror_bits(234));

Output:

112
28
87

Live Demo:

See the Pen javascript-basic-exercise-127 by w3resource (@w3resource) on CodePen.


Flowchart:

Flowchart: JavaScript - Reverse the order of the bits in a given integer

ES6 Version:

// Function to mirror bits of a given number
const mirror_bits = (n) => {
    // Convert number to binary and split into array of bits
    let t = n.toString(2).split("");

    // Get the length of the binary string
    let str_len = t.length;

    // Add leading zeroes to make the length of the binary string 8
    for (let i = 0; i < 8 - str_len; i++) {
        t.unshift("0");
    }

    // Reverse the bits and convert the binary string back to a number
    return parseInt(t.reverse().join(""), 2);
};

// Test cases with comments showing the step-by-step process
// 14 -> 00001110 -> 01110000 -> 112
console.log(mirror_bits(14));
// 56 -> 00111000 -> 00011100 -> 28
console.log(mirror_bits(56));
// 234 -> 11101010 -> 01010111 -> 87
console.log(mirror_bits(234));

Improve this sample solution and post your code through Disqus.

Previous: JavaScript program to get the largest even number from an array of integers.
Next: JavaScript program to find the smallest round number that is not less than a given value.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/javascript-exercises/javascript-basic-exercise-127.php