Skip to content

Instantly share code, notes, and snippets.

@siscia
Created July 6, 2013 10:06
Show Gist options
  • Save siscia/5939462 to your computer and use it in GitHub Desktop.
Save siscia/5939462 to your computer and use it in GitHub Desktop.
(ns base-conversion.core)
(def characters
(concat (map char (range 48 58)) (map char (range 65 91))))
(def conversion-table
(zipmap
characters
(range)))
(defn base-n-to-base-10
[^String string ^Integer base]
(let [string (clojure.string/upper-case string)]
(assert (every? #(< (conversion-table %) base) string))
(loop [num string
acc 0]
(if (seq num)
(recur (drop 1 num) (+ (* base acc) (get conversion-table (first num))))
acc))))
(defn base-10-to-base-n
[^Integer number ^Integer base]
(loop [num number
acc []]
(if (zero? num)
(clojure.string/join (reverse acc))
(recur (int (/ num base))
(conj acc (nth characters (mod num base)))))))
@siscia
Copy link
Author

siscia commented Jul 10, 2013

@rkneufeld, Oh yes, I knew that, but how you said it was just an exercise...
Actually integer/parseInt is implemented pretty much like my function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment