Class: Flt::Bits
- Inherits:
-
Object
- Object
- Flt::Bits
- Defined in:
- lib/float-formats/bytes.rb
Class Method Summary collapse
-
.from_i(v, len = nil) ⇒ Object
produce bit string from an integer.
-
.from_s(txt, base = 2, len = nil) ⇒ Object
produce bit string from a text representation.
Instance Method Summary collapse
-
#[](i) ⇒ Object
Access a bit value.
-
#[]=(i, b) ⇒ Object
Set a bit.
-
#initialize(num_bits, v = 0) ⇒ Bits
constructor
Define a bit string given the number of bits and optionally the initial value (as an integer).
-
#size ⇒ Object
number of bits.
-
#to_i ⇒ Object
convert to integer.
-
#to_s(base = 2) ⇒ Object
convert to text representation in a given base.
Constructor Details
#initialize(num_bits, v = 0) ⇒ Bits
Define a bit string given the number of bits and optionally the initial value (as an integer).
13 14 15 16 |
# File 'lib/float-formats/bytes.rb', line 13 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
49 50 51 52 |
# 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) ⇒ Object
produce bit string from a text representation
31 32 33 34 35 36 37 38 39 40 41 |
# 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 |
Instance Method Details
#[](i) ⇒ Object
Access a bit value. The least significant bit has index 0.
55 56 57 |
# File 'lib/float-formats/bytes.rb', line 55 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.
61 62 63 64 65 66 |
# 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 ⇒ Object
number of bits
69 70 71 |
# File 'lib/float-formats/bytes.rb', line 69 def size @n end |
#to_i ⇒ Object
convert to integer
44 45 46 |
# File 'lib/float-formats/bytes.rb', line 44 def to_i @v end |
#to_s(base = 2) ⇒ Object
convert to text representation in a given base
19 20 21 22 23 24 25 26 27 28 |
# 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 |