简体   繁体   中英

How to create a bit array in common lisp?

After googling for about an hour, I have to confess, that while I find a lot of documentation about functions operating on bit arrays, I cannot find a single reference on how to actually create a bit array.

Right now, it seems to me that either, some arrays with other element types can be handled as bit arrays OR that one could use (make-array:element-type (???)) where I could not find any explanation as to what to put where I wrote the "???".

So, while it is probably obvious to anyone else, I have no idea how to create a bit array. I know about how to write a literal bit array - but if I need a bit array with, say 2^16 bits - how would I do it?

You are right about using make-array , just use 'bit as the element type. Try (make-array initial-size:element-type 'bit) . The symbol BIT names the bit type and could be replaced with any other type specifier to make an array holding objects of that type. In this example initial-size is just a variable holding a whole number.

Another way to create a bit vector:

> (make-sequence '(vector bit) 10)
#*0000000000

There's also a literal syntax using the #* reader macro, and notice that the concrete type may differ between using make-array and make-sequence , though I am not sure if performance may be different depending on that...

Tested with SBCL:

CL-USER> (defvar arr (make-array 10 :element-type 'bit :fill-pointer 0))
ARR

CL-USER> (type-of arr)
(VECTOR T 10)

CL-USER> (defvar arr3 (make-sequence '(vector bit) 10))
ARR3

CL-USER> (type-of arr3)
(SIMPLE-BIT-VECTOR 10)

CL-USER> (type-of #*0101010100)
(SIMPLE-BIT-VECTOR 10)

How about this:

  • (setq x 10)
  • 10
  • (setq y (read-from-string (format nil "#*~7,'0b" x)))
  • #*0001010
  • The 7 is an arbitrary length, which could be set by
  • (setq z 8)
  • 8
  • (setq y (read-from-string (format nil (concatenate 'string "#*~" (write-to-string z) ",'0b") x)))
  • #*00001010
  • A large bit array may be better handled as an unsigned integer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM