w3resource

JavaScript: Reverse the bits of a given 16 bits unsigned short integer

JavaScript Basic: Exercise-138 with Solution

Reverse Bits in 16-Bit Unsigned Integer

Write a JavaScript program to reverse the bits of a given 16-bit unsigned short integer.

Sample Solution:

JavaScript Code:

/**
 * Function to reverse the binary representation of a 16-bit number
 * @param {number} num - The input number
 * @returns {number} - The reversed binary number
 */	
function sixteen_bits_reverse(num) {
    var result = 0; // Initialize result to store the reversed number
    for (var i = 0; i < 16; i++) {
        result = result * 2 + (num % 2); // Reversing the bits by shifting result left and adding the last bit of 'num'
        num = Math.floor(num / 2); // Right-shifting 'num' to access the next bit
    }
    return result; // Return the reversed 16-bit number
}

console.log(sixteen_bits_reverse(12345));  
console.log(sixteen_bits_reverse(10));   
console.log(sixteen_bits_reverse(5));    

Output:

39948
20480
40960

Live Demo:

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

Flowchart:

Flowchart: JavaScript - Reverse the bits of a given 16 bits unsigned short integer

ES6 Version:

/**
 * Function to reverse the bits of a number considering 16 bits
 * @param {number} num - The input number
 * @returns {number} - The result after reversing the bits (considering 16 bits)
 */
const sixteen_bits_reverse = (num) => {
	let result = 0; // Variable to store the result after reversing bits, initialized to 0
	for (let i = 0; i < 16; i++) {
		result = result * 2 + (num % 2); // Multiplying the result by 2 and adding the last bit of 'num'
		num = Math.floor(num / 2); // Dividing 'num' by 2 (integer division)
	}
	return result; // Returning the final result after reversing 16 bits
};

console.log(sixteen_bits_reverse(12345));  
console.log(sixteen_bits_reverse(10));    
console.log(sixteen_bits_reverse(5));     

Improve this sample solution and post your code through Disqus.

Previous: JavaScript program to test if a given integer is greater than 15 return the given number, otherwise return 15.
Next: JavaScript program to check whether it is possible to rearrange characters of a given string in such way that it will become equal to another given string.

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-138.php