From: "David A. Black" Date: 2009-01-29T07:10:18+09:00 Subject: Re: Bitwise question Hi -- On Thu, 29 Jan 2009, 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 Possibly more efficient since it short-circuits on the first failed bit: def check(permissions,bits) bits.all? {|bit| (permissions & 1 << bit).nonzero? } end David -- David A. Black / Ruby Power and Light, LLC Ruby/Rails consulting & training: http://www.rubypal.com Coming in 2009: The Well-Grounded Rubyist (http://manning.com/black2) http://www.wishsight.com => Independent, social wishlist management!