Class: Bits

Inherits:
Object
  • Object
show all
Defined in:
lib/bits.rb

Overview

Bits provides an easy way to store and access sequences of bits, allowing input and output in multiple formats

Instance Method Summary collapse

Constructor Details

#initialize(bits, length = 0) ⇒ Bits

bits

The bit field to store

length

Length of the bit field - default to calculated length, 0-pad on

MSB



10
11
12
13
# File 'lib/bits.rb', line 10

def initialize(bits, length = 0)
  @length = length
  @bits = bit_string_from_input(bits, length)
end

Instance Method Details

#+(bits) ⇒ Object



15
16
17
18
19
20
# File 'lib/bits.rb', line 15

def +(bits)
  bit_string_to_concat = bit_string_from_input(bits)
  length = @bits.length + bit_string_to_concat.length
  string = "0b#{@bits}#{bit_string_to_concat}"
  Bits.new(string, length)
end

#bit_stringObject



22
23
24
# File 'lib/bits.rb', line 22

def bit_string
  @bits
end

#hex_stringObject



26
27
28
# File 'lib/bits.rb', line 26

def hex_string
  "%0#{(@bits.length / 4.0).ceil}x" % @bits.to_i(2)
end

#integerObject



34
35
36
# File 'lib/bits.rb', line 34

def integer
  @bits.to_i(2)
end

#oct_stringObject



30
31
32
# File 'lib/bits.rb', line 30

def oct_string
  "%0#{(@bits.length / 3.0).ceil}o" % @bits.to_i(2)
end

#set(bits) ⇒ Object



46
47
48
# File 'lib/bits.rb', line 46

def set(bits)
  @bits = bit_string_from_input(bits, @length)
end

#signed_integerObject



38
39
40
41
42
43
44
# File 'lib/bits.rb', line 38

def signed_integer
  length_of_unsigned = @length - 1
  highest_unsigned = 2 ** length_of_unsigned
  sign_bit = (integer >> length_of_unsigned) & 1
  unsigned_portion = integer & (highest_unsigned - 1)
  (sign_bit == 1) ? -(highest_unsigned - unsigned_portion) : unsigned_portion
end