Converting decimal to hexadecimal

Started by electrifiedspam, January 02, 2011, 01:03:11 PM

Previous topic - Next topic

electrifiedspam

(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

johu

#1
> (define (hexs n w) (if w (format (string "%0" w "X") n) (format "%X" n)))
(lambda (n w)
 (if w
  (format (string "%0" w "X") n)
  (format "%X" n)))
> (hexs 255)
"FF"
> (hexs 128 4)
"0080"
>

Additionally,


> (bits 0x7F)
"1111111"
> (bits 128)
"10000000"
> (int "011" 0 2)
3
> (int "011" 0 8)
9
> (int "011" 0 10)
11
> (int "011")
9
> (int "11")
11
> (int "FF" 0 16)
255
>

http://www.newlisp.org/downloads/newlisp_manual.html#format">format, http://www.newlisp.org/downloads/newlisp_manual.html#bits">bits and http://www.newlisp.org/downloads/newlisp_manual.html#int">int are built-in and useful functions.

electrifiedspam

#2
Well,



That was more concise. I knew someone could do it. Thank you for sharing. The second part makes me feel better, because evidently there isn't a way to print hexadecimal.



Thank you for the response!

Chris

electrifiedspam

#3
Johu,



Maybe I am over thinking it but would:



(define (hexs n (w 4)) (format (string "%0" w "X") n))



be better?



Thank you for the example.

johu

#4
Thanks for improving function, Electrifiedspam.

And, Yes, it is better for your purpose.

I would like to use simply format only.

Sorry,