From: Paul Lutus Date: 2006-11-30T06:55:07+09:00 Subject: Re: One field maintaining (boolean) state of multiple items 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. -- Paul Lutus http://www.arachnoid.com