convert hex string to number

3,037 views
Skip to first unread message

Glen Rubin

unread,
Mar 27, 2010, 4:12:07 PM3/27/10
to Clojure
Hi!

I am working with a sequence of hex numbers that are in string format,

e.g.

("0x34" "0xff" "0x01" ...)


Is there a function for converting these strings into normal hex or
numbers?? I tried num, but it didn't work.

Thanks!

Richard Newman

unread,
Mar 27, 2010, 4:17:28 PM3/27/10
to clo...@googlegroups.com
> Is there a function for converting these strings into normal hex or
> numbers?? I tried num, but it didn't work.

user=> (read-string "0x44")
68

Safer:

(defn hex->num [#^String s]
(binding [*read-eval* false]
(let [n (read-string s)]
(when (number? n)
n))))

You could also use parseInt, which will be faster, so long as you can
guarantee the format:

(defn hex->num [#^String s]
(Integer/parseInt (.substring s 2) 16))

Glen Rubin

unread,
Mar 27, 2010, 5:18:27 PM3/27/10
to Clojure
thanks...you rock!!

Luc Prefontaine

unread,
Mar 27, 2010, 8:57:55 PM3/27/10
to clo...@googlegroups.com
Use a try catch around parseInt to report bad hex nb formats.
At least you'll know if you are feedind
odd values to your hex function.

Luc

Sent from my iPod

> --
> You received this message because you are subscribed to the Google
> Groups "Clojure" group.
> To post to this group, send email to clo...@googlegroups.com
> Note that posts from new members are moderated - please be patient
> with your first post.
> To unsubscribe from this group, send email to
> clojure+u...@googlegroups.com
> For more options, visit this group at
> http://groups.google.com/group/clojure?hl=en
>
> To unsubscribe from this group, send email to clojure
> +unsubscribegooglegroups.com or reply to this email with the words
> "REMOVE ME" as the subject.

Reply all
Reply to author
Forward
0 new messages