Bit banging in ruby

后端 未结 3 723
自闭症患者
自闭症患者 2021-02-10 13:24

I want to create a bit, that will contain security permissions for a given user.

In c#, I would do this by creating an enumeration, and then I would do some bit banging

3条回答
  •  情深已故
    2021-02-10 14:00

    If the underlying value is important then you can create a module that you use like an enum

    module Groups
      ADMIN = 1
      BOSS = 2
      CLERK = 4
      MEAT = 8
      BREAD = 16
      CHEESE = 32
    end
    

    To set permissions just bitwise or them together

    permissions = Groups::BOSS | Groups::MEAT | Groups::CHEESE
    

    and to test you do a bitwise and

    >> permissions & Groups::CHEESE > 0
    => true
    >> permissions & Groups::BREAD > 0
    => false
    

    I also like how you can make actual bitmasks more readable with _ like this

    permissions = 0b0010_1010
    

提交回复
热议问题