Method: Bytepack::Basic.bytesToInt
- Defined in:
- lib/bytepack/basic.rb
.bytesToInt(length, bytes, offset = 0) ⇒ Object
bytes = array of 8-bit unsigned
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
# File 'lib/bytepack/basic.rb', line 20 def bytesToInt(length, bytes, offset = 0) # bytes = array of 8-bit unsigned format = "C#{length}" format.prepend("@#{offset}") if offset > 0 bytes = bytes.unpack(format) most_significant_bit = 1 << 7 negative = (bytes[0] & most_significant_bit) != 0 unscaled_value = -(bytes[0] & most_significant_bit) << length*8-8 # Clear the highest bit # Unleash the powers of the butterfly bytes[0] &= ~most_significant_bit # Get the 2's complement (0..length-1).each {|i| unscaled_value += bytes[i] << ((length-1 - i) * 8)} unscaled_value * -1 if negative unscaled_value end |