Class: Flt::Bits

Inherits:
Object
  • Object
show all
Defined in:
lib/float-formats/bytes.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(num_bits, v = 0) ⇒ Bits

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



14
15
16
17
# File 'lib/float-formats/bytes.rb', line 14

def initialize(num_bits,v=0)
  @n = num_bits
  @v = v
end

Class Method Details

.from_i(v, len = nil) ⇒ Object

produce bit string from an integer



51
52
53
54
# File 'lib/float-formats/bytes.rb', line 51

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) ⇒ Object

produce bit string from a text representation



33
34
35
36
37
38
39
40
41
42
43
# File 'lib/float-formats/bytes.rb', line 33

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

Instance Method Details

#[](i) ⇒ Object

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



57
58
59
# File 'lib/float-formats/bytes.rb', line 57

def [](i)
  (@v >> i) & 1
end

#[]=(i, b) ⇒ Object

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



63
64
65
66
67
68
# File 'lib/float-formats/bytes.rb', line 63

def []=(i,b)
  b = (b && b!=0) ? 1 : 0
  @v &= ~(1 << i)
  @v |=  (b << i)
  b
end

#sizeObject

number of bits



71
72
73
# File 'lib/float-formats/bytes.rb', line 71

def size
  @n
end

#to_iObject

convert to integer



46
47
48
# File 'lib/float-formats/bytes.rb', line 46

def to_i
  @v
end

#to_s(base = 2) ⇒ Object

convert to text representation in a given base



20
21
22
23
24
25
26
27
28
29
30
# File 'lib/float-formats/bytes.rb', line 20

def to_s(base=2)
  n = Bits.power_of_two(base)
  if n
    fmt = Nio::Fmt.default.base(base,true).mode(:fix,:exact)
    digits = (size+n-1)/n
    fmt.pad0s!(digits)
    @v.nio_write(fmt)
  else
    @v.to_s(base)
  end
end