Created
July 14, 2019 00:09
-
-
Save danthegoodman1/121ac2b8298896db32e0f6d60e929075 to your computer and use it in GitHub Desktop.
Calculates shannon entropy in node.js
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
let raw = fs.readFileSync('./wannacrydump') | |
// console.log(raw) | |
let freqList = [] | |
console.log(`Bytes: ${raw.length}`) | |
const getEntropy = (bytes) => { | |
for (let i = 0; i < 255; i++) { | |
let ctr = 0 | |
for (byte of bytes) { | |
if (byte == i) { | |
ctr++ | |
} | |
} | |
freqList.push(ctr / bytes.length) | |
} | |
let ent = 0.0 | |
for (const [ind, freq] of freqList.entries()) { | |
if (freq > 0) { | |
ent = ent + (freq * Math.log2(freq)) | |
} | |
} | |
ent = -ent | |
console.log('Shannon entropy (min bits per byte-character):') | |
console.log(ent) | |
console.log('Min possible file size assuming max theoretical compression efficiency:') | |
console.log(ent * raw.length) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment