Jump to content

Bit fields in Ruby

mike-loukides's Photo
Posted Sep 29 2009 02:03 PM
5930 Views

I need to store very large arrays of booleans in Ruby. How do I get an array in which the elements are really only 1-bit wide? As far as I can tell, Ruby doesn't give that kind of control over storage. But an array of integer-sized booleans won't cut it. I could use a regular numeric array, with 1s and 0s and lots of shifts and masks, but that's no fun.

Tags:
2 Subscribe


2 Replies

0
  codemonky's Photo
Posted Nov 04 2009 11:33 AM

Ruby does not allow you to control the size of the objects you create. There are currently no gems that abstract out the particular problem you've described. Sad to say, but shifts as masks on integers is likely what you'll have to use for doing it in pure ruby.

The other way you could go is have a C extension provide the data manipulation and storage, but that'd be a whole other load of issues to deal with.
+ 1
  grosser's Photo
Posted Apr 25 2010 08:56 AM

i think the most efficient way would be to a string where you use each characters bits.
e.g.
"AXB" == [65, 88, 66] == [[1, 0, 0, 0, 0, 0, 1, 0] [0, 0, 0, 1, 1, 0, 1, 0], [0, 1, 0, 0, 0, 0, 1, 0]]


bits = Array.new(8){ |i| number[i] }