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))
Advertisements
Published in: on 22/12/2012 at 13:05  Comments (2)  

The URI to TrackBack this entry is: https://burubaxair.wordpress.com/2012/12/22/converting-a-list-containing-a-binary-number-to-decimal-in-lisp/trackback/

RSS feed for comments on this post.

2 CommentsLeave a comment

  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")
    (setq n (read))
    (format t"in binary : ~s" (decbin n)))


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: