Last active
February 17, 2023 19:47
-
-
Save jhmaster2000/675cdf443cc6130a7a17052718bc700e to your computer and use it in GitHub Desktop.
Basic string/buffer entropy calculator
This file contains 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
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