将数转换为基2(二进制)字符串表示形式 [英] Converting number to base-2 (binary) string representation

查看:176
本文介绍了将数转换为基2(二进制)字符串表示形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个数字转换成二进制字符串,例如(to-binary 11) - >1011。

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"

但显然没有二进制格式字符串(%b给出错误) 。

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

转换方式简单:(string-to-number10112) - > 11

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

有没有其他库函数可以这样做?

Is there any other library function to do that?

推荐答案

虽然我同意这是功能的重复,如果您在Emacs lisp中询问如何进行微调,可以阅读按位操作。这可能导致如下实现:

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

这篇关于将数转换为基2(二进制)字符串表示形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆