class MemoryIO::Types::Basic::Number

Register numbers to {Types}.

All types registered by this class are assumed as *little endian*.

This class registered (un)signed {8, 16, 32, 64)-bit integers and IEEE-754 floating numbers.

Public Class Methods

new(bytes, signed, pack_str) click to toggle source

@param [Integer] bytes

Bytes.

@param [Boolean] signed

Signed or unsigned.

@param [String] pack_str

The indicator to be passed to +Array#pack+ and +String#unpack+.
# File lib/memory_io/types/basic/number.rb, line 21
def initialize(bytes, signed, pack_str)
  @bytes = bytes
  @signed = signed
  @pack_str = pack_str
end

Public Instance Methods

read(stream) click to toggle source

@return [Integer]

# File lib/memory_io/types/basic/number.rb, line 28
def read(stream)
  unpack(stream.read(@bytes))
end
write(stream, val) click to toggle source

@param [Integer] val

# File lib/memory_io/types/basic/number.rb, line 33
def write(stream, val)
  stream.write(pack(val))
end

Private Instance Methods

pack(val) click to toggle source
# File lib/memory_io/types/basic/number.rb, line 45
def pack(val)
  [val].pack(@pack_str)
end
unpack(str) click to toggle source
# File lib/memory_io/types/basic/number.rb, line 39
def unpack(str)
  val = str.unpack(@pack_str).first
  val -= (2**(@bytes * 8)) if @signed && val >= (2**(@bytes * 8 - 1))
  val
end