Converting number to base-2 (binary) string representation [duplicate]

≯℡__Kan透↙ 提交于 2019-12-07 15:33:20

问题


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?


回答1:


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))


来源:https://stackoverflow.com/questions/20568684/converting-number-to-base-2-binary-string-representation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!