Skip to content

Instantly share code, notes, and snippets.

@flangofas
Created October 11, 2019 09:05
Show Gist options
  • Save flangofas/2a355294b9f1c9679b511db1f7475685 to your computer and use it in GitHub Desktop.
Save flangofas/2a355294b9f1c9679b511db1f7475685 to your computer and use it in GitHub Desktop.
Write a function for reversing numbers in binary. For instance, the binary representation of 13 is 1101, and reversing it gives 1011, which corresponds to number 11
//Reverse Binary
//Useful link: https://aticleworld.com/5-way-to-reverse-bits-of-an-integer/
let decimal = process.argv[2]
if (typeof decimal === "undefined") {
throw new Error('Please provide a decimal number');
}
console.log(reverseBits(new Number(decimal)))
/**
* Convert a number to binary and then reverse its bits.
*
* @param Number n
* @return Number
*/
function reverseBits(n)
{
let binary = (n >>> 0).toString(2)
let reverseBinary = binary.split('').reverse().join('')
return parseInt(reverseBinary, 2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment