Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert binary string to number

Tags:

lisp

elisp

Pretty straightforward, but I can't seem to find an answer. I have a string of 1s and 0s such as "01001010" - how would I parse that into a number?

like image 580
George Mauer Avatar asked Aug 20 '19 02:08

George Mauer


2 Answers

Use string-to-number, which optionally accepts the base:

(string-to-number "01001010" 2)
;; 74
like image 112
Amadan Avatar answered Sep 24 '22 20:09

Amadan


As explained by @sds in a comment, string-to-number returns 0 if the conversion fails. This is unfortunate, since a return value of 0 could also means that the parsing succeeded. I'd rather use the Common Lisp version of this function, cl-parse-integer. The standard function is described in the Hyperspec, whereas the one in Emacs Lisp is slightly different (in particular, there is no secondary return value):

(cl-parse-integer STRING &key START END RADIX JUNK-ALLOWED)

Parse integer from the substring of STRING from START to END. STRING may be surrounded by whitespace chars (chars with syntax ‘ ’). Other non-digit chars are considered junk. RADIX is an integer between 2 and 36, the default is 10. Signal an error if the substring between START and END cannot be parsed as an integer unless JUNK-ALLOWED is non-nil.

(cl-parse-integer "001010" :radix 2)
=> 10

(cl-parse-integer "0" :radix 2)
=> 0

;; exception on parse error
(cl-parse-integer "no" :radix 2)
=> Debugger: (error "Not an integer string: ‘no’")

;; no exception, but nil in case of errors
(cl-parse-integer "no" :radix 2 :junk-allowed t)
=> nil

;; no exception, parse as much as possible
(cl-parse-integer "010no" :radix 2 :junk-allowed t)
=> 2
like image 41
coredump Avatar answered Sep 24 '22 20:09

coredump