There is no standard way to coerce integers to bit-vectors or vice versa because Common Lisp tries to be hardware independent by all means and the binary representation of integers depends on various hard- and software specific issues like big-endian vs. little-endian, signed integers vs. unsigned integers, and if you try to simulate hardware then you also have to simulate all the various register widths and the resulting integer format overflows.

Hardware issues are usually very implementation specific, what means that there are often lots of internal functions available, so try to look-up the "Internals" section of your Common Lisp implementation's manual. But this is then no portable Common Lisp code any more.

Another good infomation source is the Lisp code of projects which deal with more hardware specific languages, e.g the

CFFI.

The "inofficial" bit-vector paper is

http://home.pipeline.com/~hbaker1/Bitvectors.htmlHere are two functions I often use to convert bit-vectors to unsigned (positive) integers and vice versa:

- Code: Select all
`(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)))

The first function is very similar to wvxvw's example, the second function first converts the integer to a list of 0 and 1 integers, and then coerces the list into a bit-vector. Using a list of integers for this is not very efficient. Also please note that there are no special type checks if the arguments are integers or bit-vectors at all, so use the functions at your own risk.

- edgar