Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

emacs

elisp

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?

like image 532
Mira Weller Avatar asked Dec 13 '13 14:12

Mira Weller


People also ask

How do you find the representation of a binary number?

To convert integer to binary, start with the integer in question and divide it by 2 keeping notice of the quotient and the remainder. Continue dividing the quotient by 2 until you get a quotient of zero. Then just write out the remainders in the reverse order.

How do you convert a string to a binary number?

To convert a string to binary, we first append the string's individual ASCII values to a list ( l ) using the ord(_string) function. This function gives the ASCII value of the string (i.e., ord(H) = 72 , ord(e) = 101). Then, from the list of ASCII values we can convert them to binary using bin(_integer) .

How do you get the binary representation of a number in Python?

To convert int to binary in Python, use the bin() method. The bin() is a built-in Python method that converts a decimal to a binary data type. The bin() function accepts a number as an argument and returns its equivalent binary string prefixed with “0b”.


1 Answers

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))
like image 176
Trey Jackson Avatar answered Nov 15 '22 04:11

Trey Jackson