Sorry about the newbie question, but I searched the web and lisp books I have and I can't find the answer to this.
Is there a easy way to convert from an integer to a bit array and vice versa?
(defun bit-vector-to-integer (bits)
(reduce #'(lambda (a b) (+ (ash a 1) b)) bits))
; example
; (bit-vector-to-integer #*11111111)
; 255
(defun bit-vector->integer (bit-vector)
"Create a positive integer from a bit-vector."
(reduce #'(lambda (first-bit second-bit)
(+ (* first-bit 2) second-bit))
bit-vector))
(defun integer->bit-vector (integer)
"Create a bit-vector from a positive integer."
(labels ((integer->bit-list (int &optional accum)
(cond ((> int 0)
(multiple-value-bind (i r) (truncate int 2)
(integer->bit-list i (push r accum))))
((null accum) (push 0 accum))
(t accum))))
(coerce (integer->bit-list integer) 'bit-vector)))
(boole boole-ior #xFF00 #x00FF) ==> #xFFFF
(boole boole-and #xFF00 #x00FF) ==> 0
(ldb (byte 4 0) #xABCD) ==> #xD
(ldb (byte 4 4) #xABCD) ==> #xC
(ldb (byte 4 8) #xABCD) ==> #xB
(ldb (byte 4 8) #xABCD) ==> #xA
(ash #x00F0 8) ==> #x0F00
(ash #x00F0 -8) ==> #x000F
(ldb (byte 4 8) #xABCD) ==> #xA
(ldb (byte 4 12) #xABCD) ==> #xA
(ash #x00F0 8) ==> #x0F00
(ash #x00F0 -8) ==> #x000F
(ash #x00F0 4) ==> #x0F00
(ash #x00F0 -4) ==> #x000F
(defun digits(n &optional (base 10))
(multiple-value-bind (q r) (floor n base)
(if (and (zerop q) (zerop r)) nil
(cons r (digits q base)))))
CL-USER> (digits 10 2)
(0 1 0 1)
CL-USER> (digits 10 8)
(2 1)
(defun reverse-digits(digits &optional (base 10) (power 0))
(if (null digits) 0
(+ (* (car digits) (expt base power)) (reverse-digits (cdr digits) base (incf power)))))
CL-USER> (reverse-digits '(0 1 0 1) 2)
10
CL-USER> (reverse-digits '(0 1 0 1) 10)
1010
Users browsing this forum: No registered users and 1 guest