Newbie question: converting from binary to decimal

could you please tell me how to convert a binary number into decimal ?
Thank you,
OS

1 Like

Do you mean a string of zero and one characters, like "1001101"?

It’s idiomatic in Clojure to leverage Java interop for stuff like parsing numbers:

dev=> (Long/parseLong "1001101" 2)
77
3 Likes

Thank you Sean. Much appreciated!

In addition to @seancorfield’s point, it’s worth noting that binary literals can be entered in this format:

2r101 ; => 5

This works for other bases, too, up through base 36:

36r1z ; => 1x36 + 35 = 71

(If anyone has the need to parse binary “decimals”, e.g. 10.011, i.e. 2.375 [2 + 1/4 + 1/8], there’s nothing in the Java or Clojure standard libraries that will parse those afaics, so you’ll need to find a special library for it or write your own. I wrote some working code to do just this, for arbitrary bases up through 36. It may be unnecessarily complicated, but if anyone’s interested I can clean it up a bit and make it into a very small library.)

4 Likes

And may I add that in ClojureScript you can do:

=> (js/parseInt "1001101" 2)
77
5 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.