Created
September 8, 2022 04:26
-
-
Save Hobadee/c89f398b823dc5edd1184cd24d289bb7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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