From: Joel VanderWerf Date: 2006-11-30T07:53:09+09:00 Subject: Re: One field maintaining (boolean) state of multiple items Paul Lutus wrote: > El Gato wrote: > >> I have a friend who posed a question to me about how to maintain the >> state of a few boolean values (radio buttons to be specific) in one >> (integer) database column. It really is more of a curious question than >> anything else, as he could simply add more columns to the table to avoid >> even thinking about it, but for the sake of fun he didn't. So, let's >> say you have three boolean values that you need to store in one field, >> and you must be able to determine what the state is (true/false) of any >> of the 3 values at any time. How would you do this? My immediate >> thought went to bit shifting or some other bit operations, but I've >> never really used anything like that before, so I'm a little stuck on >> this. Thoughts? > > Given an integer that you want to disassemble into binary bits: > > v = 15 > > Let's create an array that will contain the values of the bits: > > array = [] > > Now let's scan the integer's bits: > > 1.upto(8) do > array << (v & 1 == 1) > v >>= 1 > end > > Now the array contains 8 boolean (true/false) values corresponding to the > low 8 bits in the original integer. > irb(main):003:0> v = 15; (0..7).map {|i| v[i]} => [1, 1, 1, 1, 0, 0, 0, 0] For more info, ri 'Fixnum#[]'. But there is no #[]= (makes sense if you think about it). Another idea, storing the data in a string of length 1: require 'bit-struct' # http://redshift.sourceforge.net/bit-struct class Bits < BitStruct unsigned :bit0, 1 unsigned :bit1, 1 unsigned :bit2, 1 unsigned :bit3, 1 unsigned :bit4, 1 unsigned :bit5, 1 unsigned :bit6, 1 unsigned :bit7, 1 end b = Bits.new b.bit3 = 1 p b.bit3 # ==> 1 p b.bit4 # ==> 0 -- vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407