mdornfe1
mdornfe1

Reputation: 2150

How can I convert a length 4 byte array to an unsigned int?

I'm reading in bytes from a binary file like so

import java.io.FileInputStream

val fis = new FileInputStream(fileName)

val byteArray = new Array[Byte](4)

fis.read(byteArray)

How can I then convert the bytes in byteArray to an unsigned int?

Upvotes: 0

Views: 874

Answers (1)

Levi Ramsey
Levi Ramsey

Reputation: 20551

def bytesToInt(bytes: Array[Byte], littleEndian: Boolean): Int = {
  val buffer = java.nio.ByteBuffer.wrap(bytes)
  if (littleEndian) buffer.order(java.nio.ByteOrder.LITTLE_ENDIAN).getInt
  else buffer.getInt
}

Whether the bytes are little endian or big endian is a question of how they were written. If the bytes are in some weirder ordering (unlikely, but possible if the protocol dates back to 16-bit days), then something a lot more involved is required.

Upvotes: 1

Related Questions