BitTickler
BitTickler

Reputation: 11885

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?

Upvotes: 3

Views: 1705

Answers (4)

bitflogger
bitflogger

Reputation: 1

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.

Upvotes: -1

Renato
Renato

Reputation: 13690

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)

Upvotes: 1

Rainer Joswig
Rainer Joswig

Reputation: 139261

Another way to create a bit vector:

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

Upvotes: 4

RowPJ
RowPJ

Reputation: 529

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.

Upvotes: 4

Related Questions