Wednesday, 11 February 2009

Base 64 Decoding

For completeness.


(defn decode-num
[num]
(let [a (bit-and num 255)
b (bit-shift-right (bit-and num 65280) 8)
c (bit-shift-right (bit-and num 16711680) 16)]
(list (char c) (char b) (char a))))

(defn decode
"Lazily decode a sequence from base64"
[s]
(when-not (nil? s)
(let [x (map (fn [x] (.indexOf *encode-table* (int x))) (take 4 s))
num (+ (nth x 3) (bit-shift-left (nth x 1) 6) (bit-shift-left (nth x 2) 12) (bit-shift-left (nth x 0) 18))]
(lazy-cat (decode-num num) (decode (drop 4 s))))))


Obviously base 64 decoding is a just what we did previously, only backwards!


user> (apply str (decode (encode (decode (encode "The quick brown fox jumped over the lazy dog.")))))
"The quick brown fox jumped over the lazy dog."

No comments:

Post a Comment