I need to get all 32 bits of an Integer in Clojure into String format.
Current: (Integer/toBinaryString 10) -> "1010"
Desired: (Integer/toBinaryString 10) -> "0000000000001010"
How can I do this easily and efficiently?
For unsigned integers, you could use clojure.pprint/cl-format
directly. This example formats n
as a binary string of at least 32 characters, left padded with 0
characters:
(require '[clojure.pprint :as pp])
(defn unsigned-binary-32 [n]
(pp/cl-format nil "~32,'0B" n))
For signed integers there is a little more required:
(defn signed-binary-32 [n]
(unsigned-binary-32 (bit-and n 0xffffffff)))