Base Conversion Functions
Here I demonstrate a selection of functions to convert numbers to and from various numerical bases (i.e. conversion between numeral systems with different radixes).
The functions demonstrate how to convert a decimal integer to an arbitrary base, for example to Base 16 (Hexadecimal), Base 2 (Binary), or perhaps Base 8 (Octal); and vice-versa.
I furthermore illustrate a method to convert a number from an arbitrary base to another, for example from Base 7 (Septenary) to Base 3 (Ternary).
Decimal to Base
Select all
;; Decimal to Base - Lee Mac ;; Converts a decimal number to another base. ;; n - [int] decimal integer ;; b - [int] non-zero positive integer base ;; Returns: [str] Representation of decimal in specified base (defun LM:dec->base ( n b ) (if (< n b) (chr (+ n (if (< n 10) 48 55))) (strcat (LM:dec->base (/ n b) b) (LM:dec->base (rem n b) b)) ) )
Example Function Call
_$ (LM:dec->base 123 16) "7B" _$ (LM:dec->base 123 2) "1111011"
Base to Decimal
Select all
;; Base to Decimal - Lee Mac ;; Converts an number in an arbitrary base to decimal. ;; n - [str] string representing number to convert ;; b - [int] base of input string ;; Returns: [int] Decimal representation of supplied number (defun LM:base->dec ( n b / l ) (if (= 1 (setq l (strlen n))) (- (ascii n) (if (< (ascii n) 65) 48 55)) (+ (* b (LM:base->dec (substr n 1 (1- l)) b)) (LM:base->dec (substr n l) b)) ) )
Alternative Version
Select all
;; Base to Decimal - Lee Mac ;; Converts an number in an arbitrary base to decimal. ;; n - [str] string representing number to convert ;; b - [int] base of input string ;; Returns: [int] Decimal representation of supplied number (defun LM:base->dec ( n b ) ( (lambda ( f ) (f (mapcar '(lambda ( x ) (- x (if (< x 65) 48 55))) (reverse (vl-string->list n))))) (lambda ( c ) (if c (+ (* b (f (cdr c))) (car c)) 0)) ) )
Example Function Call
_$ (LM:base->dec "7B" 16) 123 _$ (LM:base->dec "1111011" 2) 123
Base to Base
Select all
;; Base to Base - Lee Mac ;; Converts an number from one base to another. ;; n - [str] string representing number to convert ;; b1 - [int] input base ;; b2 - [int] output base (defun LM:base->base ( n b1 b2 ) (LM:dec->base (LM:base->dec n b1) b2) )
Example Function Call
_$ (LM:base->base "7B" 16 2) "1111011" _$ (LM:base->base "1111011" 2 16) "7B"