Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What data structure for an array of bit flags?

I'm porting some imperative code to Haskell. My goal is to analyze an executable, therefore each byte of the text section gets assigned a number of flags, which would all fit in a byte (6 bits to be precise).

In a language like C, I would just allocate an array of bytes, zero them and update them as I go. How would I do this efficiently in Haskell?

In other words: I'm looking for a ByteString with bit-wise access and constant time updates as I disassemble more of the text section.

Edit: Of course, any kind of other data structure would do if it was similarly efficient.

like image 892
Sebastian Graf Avatar asked Oct 11 '14 08:10

Sebastian Graf


2 Answers

The implementation for unboxed arrays of Bool-s in array is a packed bitarray. You can do mutable updates on such arrays in the ST Monad (this is essentially the same runtime behaviour as in C).

like image 126
András Kovács Avatar answered Sep 30 '22 15:09

András Kovács


You can use a vector with any data type that's an instance of the Bits typeclass, for example Word64 for 64 bits per element in the vector. Use an unboxed vector if you want the array to be contiguous in memory.

like image 40
gspr Avatar answered Sep 30 '22 16:09

gspr