Skip to content

Instantly share code, notes, and snippets.

@siscia
Created July 6, 2013 10:06
Show Gist options
  • Select an option

  • Save siscia/5939462 to your computer and use it in GitHub Desktop.

Select an option

Save siscia/5939462 to your computer and use it in GitHub Desktop.

Revisions

  1. siscia created this gist Jul 6, 2013.
    28 changes: 28 additions & 0 deletions base-conversion-core.clj
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,28 @@
    (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)))))))