Skip to content

Instantly share code, notes, and snippets.

@Hobadee
Created September 8, 2022 04:26
Show Gist options
  • Save Hobadee/c89f398b823dc5edd1184cd24d289bb7 to your computer and use it in GitHub Desktop.
Save Hobadee/c89f398b823dc5edd1184cd24d289bb7 to your computer and use it in GitHub Desktop.
/**
* Swap the endian-ness of bits (bitLen=1), bytes (bitLen=8), or whatever bitLen you want
*
* Inspired by: https://stackoverflow.com/a/47668549
*/
function swapEndian(num, bitLen){
// Takes num, transform to binary string
let bin = num.toString(2);
let len = bin.length;
// Pad binary string with 0's in front if needed
if(len % bitLen != 0){
bin=bin.padStart(len + (bitLen - (len % bitLen)), '0');
len=bin.length;
}
const result = [];
while(len > 0){
result.push(bin.substr((len-bitLen),bitLen));
len -= bitLen;
}
let rtn = result.join('');
return parseInt(rtn,2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment