From: Joel VanderWerf Date: 2005-11-23T07:33:32+09:00 Subject: Re: How convert an integer to a bit array Curt Hibbs wrote: > Does anyone have a clever way to convert an integer to an array of bit > values? > > For example (using 8 bit integers): > > 0 => [0, 0, 0, 0, 0, 0, 0, 0] > 1 => [0, 0, 0, 0, 0, 0, 0, 1] > 2 => [0, 0, 0, 0, 0, 0, 1, 0] > 7 => [0, 0, 0, 0, 0, 1, 1, 1] > etc. > > I was looking at Array#pack and Array#unpack to do this, but haven't figured > it out yet. It just seems like there ought to be a simple way to do this. > > Anybody got a clever idea? > > Curt > s = "" s[0] = 7 s.unpack("B*")[0].split("").map{|bit|bit.to_i} => [0, 0, 0, 0, 0, 1, 1, 1] It should be easier than that, though. -- vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407