Skip to content

Instantly share code, notes, and snippets.

@serialhex
Last active May 26, 2016 19:16
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 serialhex/be260a6131acf8dee51af6a23cb6d5ee to your computer and use it in GitHub Desktop.
Save serialhex/be260a6131acf8dee51af6a23cb6d5ee to your computer and use it in GitHub Desktop.
;; here is a funky little function to parse a string representing a
;; number with any base (radix) from 2 upto 36 (0-9+a-z)
;;
;; it can even do floats in alternate bases!!
;; so "0.1" in binary = "0.5" in decimal! :-D
;; (2e(-1) = 1/2 = 0.5)
;; one note: you *need* split-sequence to use this function,
;; everything else is vanilla common lisp
(defun parse-number (str &optional (radix 10))
(labels ((to-nums (lst)
(mapcar (lambda (n) (parse-integer (string n) :radix radix))
lst))
(gt-0 (lst)
(if (null lst)
0
(parse-integer (concatenate 'string lst) :radix radix)))
(lt-0 (lst)
(if (null lst)
0
(/ (reduce (lambda (l h)
(+ h (/ l radix)))
(nreverse (to-nums lst)))
radix))))
(let* ((lsts (split-sequence "." (concatenate 'list str)))
(val (if (and (caar lsts) (char= #\- (caar lsts)))
(- (+ (gt-0 (cdar lsts)) ;; (cdr (first lsts))
(lt-0 (second lsts))))
(+ (gt-0 (first lsts))
(lt-0 (second lsts))))))
(if place
(float (* (/ place) (round val (/ place))))
(float val)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment