lib/rubyfit/helpers.rb
# Converts a fixnum or bignum into a byte array, optionally
# truncating or right-filling with 0 to match a certain size
Converts a fixnum or bignum into a byte array, optionally
truncating or right-filling with 0 to match a certain size
Converts a fixnum or bignum into a byte array optionally truncating or right - filling with 0 to match a certain size
def num2bytes(num, byte_count, big_endian = true)
    raise ArgumentError.new("num must be an integer") unless num.is_a?(Integer)
    orig_num = num
    if num < 0
      num = num.abs
      if num > 2 ** (byte_count * 8 - 1)
        STDERR.puts("RubyFit WARNING: Integer underflow for #{orig_num} (#{orig_num.bit_length + 1} bits) when fitting in #{byte_count} bytes (#{byte_count * 8} bits)")
      end
      num = 2 ** (byte_count * 8) - num
    end
    hex = num.to_s(16)
    hex = "0" + hex if hex.length.odd?
    result = [hex]
      .pack('H*')
      .unpack("C*")
    if result.size > byte_count
      STDERR.puts("RubyFit WARNING: Truncating #{orig_num} (#{orig_num.bit_length} bits) to fit in #{byte_count} bytes (#{byte_count * 8} bits)")
      result = result.last(byte_count)
    elsif result.size < byte_count
      pad_bytes = [0] * (byte_count - result.size)
      result.unshift(*pad_bytes)
    end
    result.reverse! unless big_endian
    result
  end
def num2bytes ( num , byte_count , big_endian = true ) raise ArgumentError . new ( "num must be an integer" ) unless num . is_a? ( Integer ) orig_num = num if num < 0 num = num . abs if num > 2 ** ( byte_count * 8 - 1 ) STDERR . puts ( "RubyFit WARNING: Integer underflow for #{orig_num} (#{orig_num.bit_length + 1} bits) when fitting in #{byte_count} bytes (#{byte_count * 8} bits)" ) end num = 2 ** ( byte_count * 8 ) - num end hex = num . to_s ( 16 ) hex = "0" + hex if hex . length . odd? result = [ hex ] . pack ( 'H*' ) . unpack ( "C*" ) if result . size > byte_count STDERR . puts ( "RubyFit WARNING: Truncating #{orig_num} (#{orig_num.bit_length} bits) to fit in #{byte_count} bytes (#{byte_count * 8} bits)" ) result = result . last ( byte_count ) elsif result . size < byte_count pad_bytes = [ 0 ] * ( byte_count - result . size ) result . unshift ( * pad_bytes ) end result . reverse! unless big_endian result end
Converts a fixnum or bignum into a byte array, optionally
truncating or right-filling with 0 to match a certain size
Converts a fixnum or bignum into a byte array optionally truncating or right - filling with 0 to match a certain size
# Convert negative numbers to two's complement (1-byte alignment) # pack('H*') assumes the high nybble is first, which reverses nybbles in # the most significant byte if it's only one hex char (<= 0xF). Prevent # this by prepending a zero if the hex string is an odd length
num
byte_count
big_endian