5

I'd like to convert a number to a binary string, e.g. (to-binary 11) -> "1011".

I already found a method to convert to hex and oct:

(format "%x" 11) -> "B"
(format "%o" 11) -> "13"

but there is apparently no format string for binary ("%b" gives an error).

The conversion is simple the other way round: (string-to-number "1011" 2) -> 11

Is there any other library function to do that?

Mira Weller
  • 2,406
  • 22
  • 27

1 Answers1

8

While I agree this is a duplicate of the functionality, if you're asking how to do bit-twiddling in Emacs lisp, you can read the manual on bitwise operations. Which could lead to an implementation like so:

(defun int-to-binary-string (i)
  "convert an integer into it's binary representation in string format"
  (let ((res ""))
    (while (not (= i 0))
      (setq res (concat (if (= 1 (logand i 1)) "1" "0") res))
      (setq i (lsh i -1)))
    (if (string= res "")
        (setq res "0"))
    res))
Trey Jackson
  • 73,529
  • 11
  • 197
  • 229