Skip to content

Instantly share code, notes, and snippets.

@jhmaster2000
Last active February 17, 2023 19:47
Show Gist options
  • Save jhmaster2000/675cdf443cc6130a7a17052718bc700e to your computer and use it in GitHub Desktop.
Save jhmaster2000/675cdf443cc6130a7a17052718bc700e to your computer and use it in GitHub Desktop.
Basic string/buffer entropy calculator
function entropy(strOrBuf = '') {
const buf = typeof strOrBuf === 'string' ? Buffer.from(strOrBuf, 'utf8') : strOrBuf;
const counts = {};
for (const byte of buf) {
counts[byte] ??= 0;
counts[byte] += 1;
}
let totalEntropy = 0;
for (const byte in counts) if (counts[byte]) {
const prevalence = counts[byte] / buf.byteLength;
totalEntropy += (prevalence * Math.log(prevalence) / Math.log(2)) * -1;
}
return totalEntropy;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment