(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
Converting decimal to hexadecimal
Re: Converting decimal to hexadecimal
Code: Select all
> (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"
>
Code: Select all
> (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
>
-
- Posts: 27
- Joined: Sat Nov 06, 2010 11:39 pm
Re: Converting decimal to hexadecimal
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
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
-
- Posts: 27
- Joined: Sat Nov 06, 2010 11:39 pm
Re: Converting decimal to hexadecimal
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.
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.
Re: Converting decimal to hexadecimal
Thanks for improving function, Electrifiedspam.
And, Yes, it is better for your purpose.
I would like to use simply format only.
Sorry,
And, Yes, it is better for your purpose.
I would like to use simply format only.
Sorry,