-
-
Save divoxx/391450 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Between those alternatives I'd go with this one. | |
# | |
# Ruby has open classes, there is nothing wrong about embracing them. Even Rails that used to | |
# create modules and mix them into the classes has decided to change it on rails3 and simply | |
# open the classes and add the methods. | |
# | |
# It's simple, and it works. Of course you shouldn't be adding stuff that are specific to | |
# your application's business logic. | |
class Fixnum | |
def to_bit_array | |
to_s(2).reverse.split("").map(&:to_i) | |
end | |
end | |
# Which is why I actually would change this method. Since a Fixnum is a sequence of bytes | |
# already and you just need to check if some bits are on, then I would change the method to | |
# this: | |
class Fixnum | |
# Returns true if all the given bits positions are on (set to 1) | |
# Example: | |
# 0b001110.bits_on?(1, 2, 3) | |
def bits_on?(*bits) | |
bits.all? { |n| self[n] == 1 } | |
end | |
# Adds a singular alias | |
alias_method :bit_on?, :bits_on? | |
end | |
# If you actually need to perform more calculations over the sequence of bits, I'd create a | |
# separate class for it but using composition instead of inheritance. | |
# | |
# Example: | |
# m = BitMap.new(0b001110) | |
# m.bits_on # => [1, 2, 3] | |
# m.bits_on?(1,2,3) # => true | |
class BitMap | |
def initialize(integer) | |
@integer = integer | |
end | |
# Returns true if all the given bits positions are on (set to 1) | |
# Example: | |
# 0b001110.bits_on?(1, 2, 3) | |
def bits_on?(*bits) | |
bits.all? { |n| @integer[n] == 1 } | |
end | |
# Adds a singular alias | |
alias_method :bit_on?, :bits_on? | |
# Return all the bits that are on | |
# Example: | |
# 0b001110.bits_on # => [1,2,3] | |
def bits_on | |
indexes = [] | |
(0...@integer.size*8).each { |n| indexes << n if @integer[n] == 1 } | |
indexes | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Oh, and if the bit string was bigger then transforming the integer to a string, then to an array, then reverse, then map would definitely take longer.
Using the number 0xffffffffffffffffffffffff: