## Converting a list containing a binary number to decimal in Lisp

For example, you want to convert:

(1 0 1) —> 5
(1 1 0 1 0 1 0 1) —> 213
etc

It can be done as follows:

```
;;converts binary list to decimal
(defun bin-list-to-dec (lst)
(if (bin-list-p lst)
(reduce (lambda (x y) (+ (* x 2) y)) lst)
nil))
```

The function `bin-list-p` checks if the argument is a non-empty binary list:

```
;;checks if the list's elements are only 0's and 1's
(defun bin-list-p (lst)
(if (and (listp lst) (not (null lst)))
(every #'(lambda (x) (or (zerop x) (onep x) )) lst)
nil))
```

I put `(onep x)` instead of `(= 1 x)` because it looks nicer here together with `(zerop x)`.

`onep` is simply

```
;; checks if the argument is 1
(defun onep (x)
(= x 1))
```
Published in: on 22/12/2012 at 13:05  Comments (2)

1. Thank you

2. what’s wrong with this code?

(defun decbin (n)

(let ((i) (k 0) (v (make-array ‘(25))))
(loop
(setq i (mode n 2))
(setf (aref v k) i)
(setq n (truncate (/ n 2)))
(when (= n 0) (return)))

(do ((i (- k 1)) (- i 1))
((< n 0))
(format t"~s" (aref v i)))))

(prog (n)
(format t"Input a decimal number")