Skip to content

Instantly share code, notes, and snippets.

@tonygaetani tonygaetani/binconv.clj
Last active Nov 13, 2015

Embed
What would you like to do?
(defn pow2 [n]
"Returns a long representing 2^n"
(->> n (Math/pow 2) long))
(defn b10->b2
"Converts a base 10 number to a lazy seq of 1's and 0's that make up a base 2 number"
([n] (b10->b2 n '()))
([n col]
(if (= 1 n)
(merge col 1) ; base case
(let [r (mod n 2)]
(b10->b2 (->> (/ n 2) Math/floor long) (merge col r))))))
(defn b2->b10 [col]
"Converts a seq of 1's and 0's that make up a base 2 number into a base 10 number"
(when (seq col)
(reduce + (map #(if (zero? (second %)) 0 (pow2 (first %))) (map-indexed vector (reverse col))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.