Skip to content

Instantly share code, notes, and snippets.

@divoxx
Forked from norman/gist:391224
Created May 5, 2010 21:21
Show Gist options
  • Save divoxx/391450 to your computer and use it in GitHub Desktop.
Save divoxx/391450 to your computer and use it in GitHub Desktop.
# 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
@divoxx
Copy link
Author

divoxx commented May 6, 2010

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:

Rehearsal ---------------------------------------------------
Module method :   0.000000   0.000000   0.000000 (  0.000200)
BitMap class  :   0.000000   0.000000   0.000000 (  0.000121)
------------------------------------------ total: 0.000000sec

                      user     system      total        real
Module method :   0.000000   0.000000   0.000000 (  0.000129)
BitMap class  :   0.000000   0.000000   0.000000 (  0.000054)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment