class Flt::Bits

Public Class Methods

from_i(v, len=nil) click to toggle source

produce bit string from an integer

# File lib/float-formats/bytes.rb, line 49
def self.from_i(v, len=nil)
  len ||= (Math.log(v)/Math.log(2)).ceil # v.to_s(2).size
  Bits.new(len,v)
end
from_s(txt,base=2,len=nil) click to toggle source

produce bit string from a text representation

# File lib/float-formats/bytes.rb, line 31
def self.from_s(txt,base=2,len=nil)
  txt = txt.tr('., _','')
  v = txt.to_i(base)
  if len.nil?
    n = power_of_two(base)
    if n
      len = txt.size * n
    end
  end
  from_i v, len
end
new(num_bits, v=0) click to toggle source

Define a bit string given the number of bits and optionally the initial value (as an integer).

# File lib/float-formats/bytes.rb, line 13
def initialize(num_bits, v=0)
  @n = num_bits
  @v = v
end

Protected Class Methods

is_power_of_two?(v) click to toggle source
# File lib/float-formats/bytes.rb, line 75
def self.is_power_of_two?(v)
  if v==0
    false
  else
    v &= (v-1)
    if v==0
      true
    else
      false
    end
  end
end
power_of_two(v) click to toggle source
# File lib/float-formats/bytes.rb, line 88
def self.power_of_two(v)
  if is_power_of_two?(v)
    n = 0
    while v!=1
      n += 1
      v >>= 1
    end
    n
  else
    nil
  end
end

Public Instance Methods

[](i) click to toggle source

Access a bit value. The least significant bit has index 0.

# File lib/float-formats/bytes.rb, line 55
def [](i)
  (@v >> i) & 1
end
[]=(i,b) click to toggle source

Set a bit. The least significant bit has index 0. The bit value can be passed as an integer or a boolean value.

# File lib/float-formats/bytes.rb, line 61
def []=(i,b)
  b = (b && b!=0) ? 1 : 0
  @v &= ~(1 << i)
  @v |=  (b << i)
  b
end
size() click to toggle source

number of bits

# File lib/float-formats/bytes.rb, line 69
def size
  @n
end
to_i() click to toggle source

convert to integer

# File lib/float-formats/bytes.rb, line 44
def to_i
  @v
end
to_s(base=2) click to toggle source

convert to text representation in a given base

# File lib/float-formats/bytes.rb, line 19
def to_s(base=2)
  n = Bits.power_of_two(base)
  if n
    digits = (size+n-1)/n
    #{ }"%0#{digits}d" % @v.to_s(base)
    Numerals::Format[:fix, base: base].set_leading_zeros(digits).write(@v)
  else
    @v.to_s(base)
  end
end