Arc Forumnew | comments | leaders | submitlogin
Q: How to convert decimal to hex?
1 point by newb 5781 days ago | 1 comment
I need to convert decimal number to hex string, padded with 0's. For example:

  1 -> "01"
  242 -> "f2"
Should I write my own procedure or is there something built in?

Thank you.



4 points by aw 5781 days ago | link

Built in is (coerce i 'string 16) which will convert a number to a hex string; then you can pad it with zeros yourself.

  (def bytehex (i)
    (if (< i 16) (writec #\0))
    (pr (upcase:coerce i 'string 16)))

  (bytehex 1) prints 01
  (bytehex 242) prints F2
You can leave out the "upcase" to get "f2" instead of "F2".

To get a string, you can use "tostring" with bytehex:

  arc> (tostring (bytehex 1))
  "01"
or else produce a string directly:

  (def 2hex (i)
    (string (if (< i 16) #\0) (coerce i 'string 16)))

  arc> (2hex 1)
  "01"
  arc> (2hex 242)
  "f2"

-----