nbase.lsp Version 1.00 10 June 2005 Author Steven Jones Contact jones57@swbell.net include the word "nyquist" in subject line The contents of this file are released under the terms of the GNU General Public License. See the file LICENSE.txt Number base conversion
function
(nbase n [b]) Convert decimal number n to base b. n - Integer. The number to be converted b - Integer. The number base of the result. The function operates up to base 36, default 10 return - String. The string representation of n in base b.
function
(nbase:->decimal n [b]) Convert string representation of base b number n to decimal. n - String. The number in base b to be converted. b - Integer. The number base of n, 2,3,4...36, default 10 return - Integer. The decimal value of n.
;; nbase.lsp ;; Version 1.00 10 June 2005 ;; Author Steven Jones ;; ;; Contact jones57@swbell.net include the word "nyquist" in subject line ;; ;; The contents of this file are released under the terms of the GNU General ;; Public License. See the file LICENSE.txt ;; ;; Number base conversion ;; (provide 'nbase) (current-file "nbase") (setq nbase:*tab* (list "0" "1" "2" "3" "4" "5" "6" "7" "8" "9" "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" "U" "V" "W" "X" "Y" "Z")) (setq nbase:*max-base* (1+ (length nbase:*tab*))) ;; @doc function nbase ;; (nbase n [b]) ;; Convert decimal number n to base b. ;; ;; n - Integer. The number to be converted ;; b - Integer. The number base of the result. ;; The function operates up to base 36, default 10 ;; return - String. The string representation of n in base b. ;; (defun nbase (n &optional (b 10)) (assert (and (integerp n)(integerp b)(> b 1)(< b nbase:*max-base*)) (format nil "nbase: Invalid argument n=~a b=~a" n b)) (cond ((minusp n) (strcat "-" (nbase (abs n) b))) ((zerop n) "0") (t (let ((acc "")) (while (plusp n) (setf acc (strcat (nth (rem n b) nbase:*tab*) acc)) (setf n (/ n b))) acc)))) ;; @doc function nbase:->decimal ;; (nbase:->decimal n [b]) ;; Convert string representation of base b number n to decimal. ;; ;; n - String. The number in base b to be converted. ;; b - Integer. The number base of n, 2,3,4...36, default 10 ;; return - Integer. The decimal value of n. ;; (defun nbase:->decimal (n &optional (b 10)) (assert (and (stringp n)(integerp b)(> b 1)(< b nbase:*max-base*)) (format nil "nbase:->decimal invalid argument n=~a b=~a" n b)) (let (acc digit weight cindex coefficient) (setf n (string-upcase n)) (setf acc 0) (dotimes (i (length n)) (setf digit (subseq n i (1+ i))) (setf weight (expt (float b) (- (length n) i +1))) (setf coefficient (locate nbase:*tab* digit :test #'string=)) (assert (and coefficient (< coefficient b)) (format nil "nbase:->decimal ~a is not a valid base ~a number." n b)) (setf acc (+ acc (* coefficient weight)))) (truncate acc)))