Last active
November 17, 2015 11:30
-
-
Save lepoetemaudit/36fc27c9b60454d7cf02 to your computer and use it in GitHub Desktop.
Huffman string decoder in clojure
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
(defn- decode-huffman [nodes buffer] | |
(string/join (loop [byte-pos 0 bits (first buffer) | |
node (last nodes) | |
bits-remaining 8 output []] | |
(if (= 0 bits-remaining) | |
(recur (inc byte-pos) (nth buffer (inc byte-pos)) node 8 output) | |
(let [next-node (if (bit-test bits 7) :right :left)] | |
(if (= 255 (:right node)) | |
(if (not= (:value node) "|") | |
(recur byte-pos bits | |
(last nodes) bits-remaining | |
(conj output (:value node))) | |
output) | |
(recur byte-pos ; current byte pos | |
(bit-and 255 (bit-shift-left bits 1)) | |
(nth nodes (next-node node)) ; next node in huffman tree | |
(dec bits-remaining) | |
output))))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment