Search code examples
ruby-on-railsrubybitmask

Compare binary integers ruby


I am working with a master bitmask in Ruby that contains a list of settings. I have converted the bitmask to binary and need to compare it to other binary values to see if certain setting exists.

For example, I start with the bitmask:

bitmask = 1540104

Then convert to binary using:

binary = bitmask.to_s(2) => 101111000000000001000

Since each 1 in that master binary represents a single setting, how can I iterate over that result to see each 1's placement in the context of the 21 digit binary? Like so:

100000000000000000000
001000000000000000000
000100000000000000000
000010000000000000000
000001000000000000000
000000000000000001000

Any help would be much appreciated!


Solution

  • how can I iterate over that result to see each 1's placement in the context of the 21 digit binary?

    If you just want to see the bits, i.e. for debugging purposes, you could solve it via Integer#bit_length, Integer#[] and some bit shifting:

    bitmask = 1540104
    
    bitmask.bit_length.downto(0) do |n|
      printf("%.*b\n", bitmask.bit_length, 1 << n) unless bitmask[n].zero?
    end
    

    Output:

    100000000000000000000
    001000000000000000000
    000100000000000000000
    000010000000000000000
    000001000000000000000
    000000000000000001000