From: Rob Biedenharn Date: 2009-01-29T07:07:29+09:00 Subject: Re: Bitwise question On Jan 28, 2009, at 4:32 PM, Pascal J. Bourguignon wrote: > Andrew Barringer writes: > >> I'm working on a project that has a bitmap of permissions and I >> need to >> find out if a user has access. >> >> >> >> Given permissions bit mask of 0001C0200F02000000000 where each bit >> represents a specific permission >> >> >> >> And a request for permissions check on bits [37, 12, 48] >> >> >> >> What's the best way to find out if user has access to all requested >> permissions? > > > (def check(permissions,bits) > (bits . inject(true) { | r , b | > (r and (0 != (permissions & (1 << b)))) > }) > end) > nil > (check 0xf0,[1,4,5,6]) -> false > (check 0xf0,[4,5,6]) -> true > > -- > __Pascal Bourguignon__ Or a simpler version: class Integer def as_bits ary = [] (self.size*8).times {|i| ary.unshift(i) if self[i].nonzero?} ary end def check_permissions(*bits) bits.all? {|bit| self[bit].nonzero? } end end irb> 0x0001C0200F02000000000.as_bits => [68, 67, 66, 57, 47, 46, 45, 44, 37] irb> 0x0001C0200F02000000000.check_permissions 37, 12, 48 => false irb> 0x0001C0200F02000000000.check_permissions 37, 47, 57 => true And written in normal Ruby rather than LispRuby ;-) -Rob Rob Biedenharn http://agileconsultingllc.com Rob@AgileConsultingLLC.com