Skip to content

Instantly share code, notes, and snippets.

@elomatreb
Created March 22, 2017 08:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elomatreb/b1e0a7d58ada4147c7bbcbc994efc0f0 to your computer and use it in GitHub Desktop.
Save elomatreb/b1e0a7d58ada4147c7bbcbc994efc0f0 to your computer and use it in GitHub Desktop.
Ruby utility for parsing bitmask options.
# Usage:
# Bitmask[:list, :of, :option, :keys, value]
# where the last key in the list will be represented by the least significant
# bit in value.
#
# Example:
# Bitmask[:optionA, nil, :optionB, :optionC, 0b1010]
# #=> {:optionA=>true, :optionB=>true, :optionC=>false}
# Use nils to indicate bits that do not have a meaning.
class Bitmask
def self.[](*fields, bitmask)
unless bitmask.is_a? Integer
raise ArgumentError,
"A bitmask can only be an Integer, #{bitmask.class} given"
end
Hash[
fields.map.with_index(1) do |field, bit|
next unless field
[field, bitmask & (1 << fields.size - bit) > 0]
end.compact
]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment