exupero's blog
RSSApps

Clojure radix literals

Most programming languages interpret sequences of digits as base-10 numbers. Python adds syntax for the common alternate bases of binary, octal, and hexadecimal, which can be written with the prefixes 0b, 0o, and 0x, respectively (as in 0b10010 = 18, 0o16 = 14, and 0xff = 255). Clojure, however, is the only language I know that offers a built-in literal syntax for any base between 2 and 36.

To do so, it provides what is essentially an infix operator, r. The digits to the left of the r define the base (or radix), and the digits to the right define the number itself. For example, the binary, octal, and hexadecimal numbers given above can be expressed like this:

2r10010
18
8r16
14
16rff
255

Uppercase R also works:

2R10010
18

For bases above 10, Clojure interprets letters as digits greater than nine, as is common with hexadecimal numbers, but it extends the scheme beyond F = 15:

17rG
16

That behavior reveals why radix literals only work up to base-36: the Latin alphabet only has 26 letters.

36rZ
35

In practice, I don't recall ever using any base other than binary, octal, or hexadecimal, but if you have, let me know.