Convert number to base-2 (binary) string representation

I would like to convert a number to a binary string for example. (to-binary 11) → "1011".

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

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

      

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

The conversion is just the other way around: (string-to-number "1011" 2) → 11

Is there any other library function?

+2


source to share


1 answer


While I agree that this is a duplicate of functionality, if you are asking how to do bit-twiddling in Emacs lisp, you can read the manual on bitwise operations . This can lead to implementation like this:



(defun int-to-binary-string (i)
  "convert an integer into it 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))

      

+3


source







All Articles