Converting decimal to hexadecimal
Posted: Sun Jan 02, 2011 9:03 pm
(define (to-hex number)
(set 'answer '())
(while (> number 0)
(cond ((> number 0) (set 'answer (append (list (hex-let (mod number 16))) answer)) (set 'number (/ number 16)))
((= number 0) (set 'answer (append (list (hex-let (mod number 16))) answer)))
)
)
(join (map string answer))
)
(define (hex-let num)
(cond ((= num 10) (set 'num "A"))
((= num 11) (set 'num "B"))
((= num 12) (set 'num "C"))
((= num 13) (set 'num "D"))
((= num 14) (set 'num "E"))
((= num 15) (set 'num "F"))
)
num
)
-----------------------------------------------------------------------------------------------------------------------
I couldn't find a ready way to do this in the language, not that there isn't one. But there comes a time when it is just easier to roll your own rather than search. This returns a string that represents the hexadecimal value of the decimal number you put into it.
I was trying to read error messages coming back to me from the PLC. (map char (explode buff)) helpfully converted all of the values to decimal which while nice, made it difficult to compare to the hexadecimal message I had sent.
I don't think that you really NEED this for production code, but it sure was nice for trouble shooting.
Again, I am sure that there is a better way, but this was fun.
Chris
(set 'answer '())
(while (> number 0)
(cond ((> number 0) (set 'answer (append (list (hex-let (mod number 16))) answer)) (set 'number (/ number 16)))
((= number 0) (set 'answer (append (list (hex-let (mod number 16))) answer)))
)
)
(join (map string answer))
)
(define (hex-let num)
(cond ((= num 10) (set 'num "A"))
((= num 11) (set 'num "B"))
((= num 12) (set 'num "C"))
((= num 13) (set 'num "D"))
((= num 14) (set 'num "E"))
((= num 15) (set 'num "F"))
)
num
)
-----------------------------------------------------------------------------------------------------------------------
I couldn't find a ready way to do this in the language, not that there isn't one. But there comes a time when it is just easier to roll your own rather than search. This returns a string that represents the hexadecimal value of the decimal number you put into it.
I was trying to read error messages coming back to me from the PLC. (map char (explode buff)) helpfully converted all of the values to decimal which while nice, made it difficult to compare to the hexadecimal message I had sent.
I don't think that you really NEED this for production code, but it sure was nice for trouble shooting.
Again, I am sure that there is a better way, but this was fun.
Chris