Skip to content

Instantly share code, notes, and snippets.

@lepoetemaudit
Last active November 17, 2015 11:30
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 lepoetemaudit/36fc27c9b60454d7cf02 to your computer and use it in GitHub Desktop.
Save lepoetemaudit/36fc27c9b60454d7cf02 to your computer and use it in GitHub Desktop.
Huffman string decoder in clojure
(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