class ASMOperations::Binary

Attributes

binary[RW]
bit_count[RW]
errors[RW]
warnings[RW]

Public Class Methods

new(unsigned_binary) click to toggle source
# File lib/types/binary.rb, line 5
def initialize(unsigned_binary)
  @errors, @warnings = [], []
  @binary = unsigned_binary
  @bit_count = count_bits and unsigned?
  fix_bytes
end

Public Instance Methods

to_decimal() click to toggle source
# File lib/types/binary.rb, line 12
def to_decimal
  bits_powers.reduce(0) do |acc, pow|
    acc += 2**pow
  end
end
to_hex() click to toggle source
# File lib/types/binary.rb, line 18
def to_hex
  binary.split('').each_slice(4).to_a.map do |binary_slice|
    decimal = Binary.new(binary_slice.join('')).to_decimal
    ASMOperations::HEX_TABLE.invert[decimal]
  end.join('')
end

Private Instance Methods

bits_powers() click to toggle source
# File lib/types/binary.rb, line 33
def bits_powers
  @binary.split('').reverse.map.with_index(0).to_a.map do |object|
    next if object.first == '0'
    object.last
  end.compact
end
count_bits() click to toggle source
# File lib/types/binary.rb, line 45
def count_bits
  case @binary.split('').length
  when 1..4
    4
  when 5..8
    8
  when 9..16
    16
  when 17..32
    32
  when 33..64
    64
  else
    @errors.push 'Not an 8 || 16 || 32 || 64  bit'
    0
  end
end
fix_bytes() click to toggle source
# File lib/types/binary.rb, line 27
def fix_bytes
  return false if @binary.length == bit_count || bit_count == 0
  remaining_bits = bit_count - @binary.length
  @binary = Array.new(remaining_bits) { '0' }.join('') + @binary
end
unsigned?() click to toggle source
# File lib/types/binary.rb, line 40
def unsigned?
  return if @binary.split('').first == '0'
  @warnings << 'Number is a signed one'
end