Skip to content

Instantly share code, notes, and snippets.

@aaronpeterson
Last active December 18, 2022 00:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aaronpeterson/7813ca69de30d8c1d4a4015db0e39308 to your computer and use it in GitHub Desktop.
Save aaronpeterson/7813ca69de30d8c1d4a4015db0e39308 to your computer and use it in GitHub Desktop.
Javascript bitf*ckery because I hate bits and reading data sheets for i2c stuffs and I'm also jealous of python etc
// console.log(bitmagic("b[1010]d[3,2]h[02,2]"));
// console.log(bitmagic("b[10]d[1,2]h[0A]"));
/**
* Bitmagic the Freewheelin' bitmiser
*
* Use any combination of bits, numbers or hex and output a nice-lookin' byte
*
* Usage: b[binary]d[decimal,padding?]h[hex,padding?]
*
* b[1010]d[3,2]h[02,2] = 10101110
* b[10]d[1,2]h[0A] = 10011010
*
* {b, d, h}
*/
function bitmagic(str) {
let matches = [...str.matchAll(/([dbh]{1})\[([^\]]+)\]/g)];
let b = matches.reduce((a, e) => {
let [val, pad] = e[2].split(',');
if (e[1] === "b") {
// nothing to do
a += `${val}`;
} else if (e[1] === "d") {
a += (val >>> 0).toString(2).padStart(pad ? pad : 0, '0');
} else if (e[1] === "h") {
a += `${parseInt(val, 16).toString(2).padStart(pad ? pad : 0, '0')}`
}
return a;
}, "");
return {b: b, d: parseInt(b, 2), h: '0x' + parseInt(b,2).toString(16)};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment