Module: BitUtils::PureRuby

Defined in:
lib/bit_utils/pure_ruby.rb

Overview

Note:

not intended for direct use.

module for pure Ruby code of BitUtils.

Class Method Summary collapse

Class Method Details

.each_bit(num) ⇒ Object

Raises:

  • (TypeError)


34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/bit_utils/pure_ruby.rb', line 34

def each_bit(num)
  raise TypeError unless num.is_a?(::Integer)
  raise RangeError if num < 0
  return enum_for(__method__, num) { BitUtils.count(num) } unless block_given?
  shift = 0
  loop do
    return if num == 0
    pos = BitUtils.trailing_zeros num
    yield shift + pos
    num >>= pos + 1
    shift += pos + 1
  end
end

.popcount(num) ⇒ Object

Raises:

  • (TypeError)


16
17
18
19
20
# File 'lib/bit_utils/pure_ruby.rb', line 16

def popcount(num)
  raise TypeError unless num.is_a?(::Integer)
  return -popcount(~num) if num < 0
  num.to_s(2).count('1')
end

.trailing_zeros(num) ⇒ Object

Raises:

  • (TypeError)


25
26
27
28
29
# File 'lib/bit_utils/pure_ruby.rb', line 25

def trailing_zeros(num)
  raise TypeError unless num.is_a?(::Integer)
  return -1 if num == 0
  (num & -num).bit_length - 1
end