Class: Numeric

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

Instance Method Summary collapse

Instance Method Details

#to_bytes(order: :BE) ⇒ Symbol

Convert an integer non-negative number that to bytes array using specified endianness. if it is float, it will be converted to an integer first.



11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/ttcrypt.rb', line 11

def to_bytes order: :BE
  order == :BE || order == :LE or raise ArgimentError, "unkown order, should be either :BE or :LE"
  (value  = self.to_i) < 0 and raise ArgumentError, 'value must not be negative'
  result = ''
  result.force_encoding 'binary'
  while value != 0
    byte  = value & 0xFF
    value >>= 8
    result << byte.chr
  end
  result == '' ? "\x0" : (order == :BE ? result.reverse : result)
end