Sat, 30th Aug 2008 09:27:20
Never fear, this site is here

#dec2hex.lisp

Language: Common LISP
Written by doug on 2008-02-17 18:45:59

;
; dec2hex.lisp
; author: doug@neverfear.org
; date: 27 January 2008
; last modified: 17 February 2008
; language: Common LISP
;
; This file shows a LISP implementation of a dec2hex algorithm I developed
; while working in a proprietary language called LEO. I had to develop a
; decimal to hexadecimal data representation conversion routine because the
; language did not have such a feature, nor did it have bitwise operators
; to easily extract the bit pattern and represent that.
;
; The original LEO expression I can not show for legal reasons but LEO has
; a similar style to LISP.
;
; The story behind my working is rather bizarre. I was thinking for a long
; time how to develop my own bitwise operators and then build a routine 
; which would utilize them to produce the result. After 30 minutes or so
; going down that path. I stopped, had this moment of pure clarity that I
; still can't seem to recreate and wrote this algorithm down.
;
; Usage:
; clisp dec2hex.lisp <a decimal integer>
;
; Example:
; $ clisp dec2hex.lisp 23423479823
; In: 23423479823
; Out: 0x57425F00F
; 
; Note: If a invalid decimal integer is supplied, but there are valid 
; decimal integer characters at the beginning of the argument then this
; code truncates the value at the first character which is not 0-9.
; 

(defun dec2hex(v)
	(if (< v 16)
		(if (< v 10)
		  	(write-to-string v)
			(string (int-char (+ 55 v)))
		)
		(concatenate
			'string
			(dec2hex (floor (/ v 16)))
			(dec2hex (mod v 16))
		)
	)	
)
(let
	(
		(in (first EXT:*ARGS*))
	)
	(format t "In: ~a~%" in)
	(let
		(
			(x (parse-integer in :junk-allowed t))
		)
		(if x
			(format t "Out: 0x~a~%" (dec2hex x))
			(format t "Error: '~a' is not a valid decimal integer value" in)
		)
	)
)

Powered by Debian, Jack Daniels, Guinness, and excessive quantities of caffeine and sugar.