Reading little-endian unsigned integers


I’m reading BGZF and tabix index headers, which consist of little-endian unsigned and signed integers of various sizes (8-, 16-, 32- and 64-bit).

I’m reading the data into a java.nio.ByteBuffer.

Is there some support in Scala for reading little-endian and/or unsigned integers from binary data?


 Best, Oliver


Thanks for the response! I figured out how to read my data.

Regarding endianness, ByteBuffer has a method to set endianness aka byte order.

I then use the regular ByteBuffer methods to read the data as signed integers and calculate the intended unsigned values as necessary. Since Scala/Java/JVM assume two’s complement as integer encoding:

  • if the read value is positive, it is the intended value

  • if the read value is negative, it is the intended value minus two to the power of the number of bits

Masking bits is more efficient:

val signedInt = -4325435
val unsignedLong = signedInt & (1L << 32) - 1