Class: Integer

Inherits:
Object show all
Defined in:
lib/mug/bittest.rb

Instance Method Summary collapse

Instance Method Details

#and?(other, test: :any) ⇒ Boolean

Tests common bits in this AND other.

test:

:any  => true if any bits are set
:all  => true if all bits are set

Examples:

require 'mug/bittest'
0b1010.and?(0b1000, test: :any)  #=> true
0b1010.and?(0b1100, test: :all)  #=> false

Parameters:

  • other (Integer)

    the bitmask to test against

  • test (Symbol) (defaults to: :any)

    :any or :all

Returns:

  • (Boolean)

    whether the bit test passes

Raises:

  • (ArgumentError)

    if test is not :any or :all

See Also:



24
25
26
27
28
29
30
31
32
33
# File 'lib/mug/bittest.rb', line 24

def and? other, test: :any
  case test.to_sym
  when :any
    and_any? other
  when :all
    and_all? other
  else
    raise ArgumentError, "invalid value for 'test' (given #{test.inspect}, should be :any or :all)"
  end
end

#and_all?(other) ⇒ Boolean

Note:

Similar to Integer#allbits? (Ruby 2.5+).

True if this AND other is other.

i.e. if all set bits in other are set in this.

Examples:

require 'mug/bittest'
0b1110.and_all?(0b1010)  #=> true
0b1010.and_all?(0b1100)  #=> false

Parameters:

  • other (Integer)

    the bitmask to test against

Returns:

  • (Boolean)

    whether all set bits in other are set in this



70
71
72
73
# File 'lib/mug/bittest.rb', line 70

def and_all? other
  return false if other.zero?
  self & other == other
end

#and_any?(other) ⇒ Boolean

Note:

Similar to Integer#anybits? (Ruby 2.5+).

True if this AND other is non-zero.

i.e. if any set bits in other are set in this.

Examples:

require 'mug/bittest'
0b1010.and_any?(0b1000)  #=> true
0b1010.and_any?(0b0100)  #=> false

Parameters:

  • other (Integer)

    the bitmask to test against

Returns:

  • (Boolean)

    whether any set bits in other are set in this



50
51
52
53
# File 'lib/mug/bittest.rb', line 50

def and_any? other
  return false if other.zero?
  self & other != 0
end

#or?(other) ⇒ Boolean

Note:

No stdlib equivalent exists.

True if this OR other is non-zero.

Examples:

require 'mug/bittest'
0b1010.or?(0b0000)  #=> true
0b0000.or?(0b0000)  #=> false

Parameters:

  • other (Integer)

    the value to OR with

Returns:

  • (Boolean)

    whether this OR other is non-zero



88
89
90
# File 'lib/mug/bittest.rb', line 88

def or? other
  self | other != 0
end

#xor?(other) ⇒ Boolean

Note:

No stdlib equivalent exists.

True if this XOR other is non-zero.

Examples:

require 'mug/bittest'
0b1010.xor?(0b1010)  #=> false
0b1010.xor?(0b0101)  #=> true

Parameters:

  • other (Integer)

    the value to XOR with

Returns:

  • (Boolean)

    whether this XOR other is non-zero



105
106
107
# File 'lib/mug/bittest.rb', line 105

def xor? other
  self ^ other != 0
end