16

We can represent the number 12 as 2r001100 in clojure.

Is there a built-in function to print 2r001100 when given the number 12?

5 Answers 5

28

java.lang.Integer/toString will print numbers with arbitrary radix:

(Integer/toString 0xf2 2)  ==> "11110010"
(Integer/toString 0xf2 16) ==> "f2"
(Integer/toString 0xf2 27) ==> "8q"
1
  • If you need the binary representation with leading zeros you can use (-> 0x7 (Integer/toString 2) (Integer/parseInt) (->> (format "%04d"))) that will result in 0111.
    – Jp_
    Apr 1, 2021 at 12:41
14

see cl-format

user=> (require '[clojure.pprint :refer (cl-format)])
nil
user=> (cl-format nil "2r~6,'0',B" 12)
"2r001100"
1
  • 3
    This is great, but will not print the two's complement representation of the number for a negative input.
    – noisesmith
    Jan 30, 2014 at 17:19
8

These functions generate and print strings using java.util.Formatter.

But they don't do binary, so the best I could come up with is:

(fn [i] (str "2r" (Integer/toBinaryString i)))
0
4

All of these answers are good, but either won't support two's-complement for negative numbers (cl-format), or won't print out the correct number of bits based on the width of the data itself (e.g., calling Integer/toBinaryString or Integer/toString on a byte will not do what you want, especially for negative numbers).

Here's a solution that will correctly print out the exact bits of the underlying data:

(defn print-bits [b]
  (let [class-name (.getName (class b))
        is-byte (= "java.lang.Byte" class-name)
        num-bits (clojure.lang.Reflector/getStaticField class-name "SIZE")
        format-string (str "~" num-bits "'0b")
        bin-str-fn #(clojure.lang.Reflector/invokeStaticMethod
                     (if is-byte "java.lang.Integer" class-name)
                     "toBinaryString"
                     (to-array [%]))
        bit-string (if is-byte
                     (str/join (take-last 8 (bin-str-fn (Byte/toUnsignedInt b))))
                     (bin-str-fn b))]
    (println (str (str/join (repeat (- num-bits (count bit-string)) \0))
                  bit-string))))
2

Test of extremes here, using (bit-shift-left 1 63), or 1000000000000000000000000000000000000000000000000000000000000000.

The cl-format solution provided gives me an integer overflow.

Integer/toBinaryString gives me Value out of range for int: -9223372036854775808.

But Long/toBinaryString gives me the string that I expected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.