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?
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.
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) .
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”.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With