0

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?

mdornfe1
  • 1,982
  • 1
  • 24
  • 42
  • That depends on what that bytes represent – Piro Dec 25 '17 at 06:34
  • @Piro How so? In the documentation for the file it says the 4 bytes represent an unsigned int. – mdornfe1 Dec 25 '17 at 06:41
  • I do not see any documentation to refer to. integer can be represented in 4 bytes in a lot of ways. @twentyseven already assumed bytes represent 4 digit characters. That brings encoding into game. Then integer can be stored simply as 32bites binary number, and many more – Piro Dec 25 '17 at 06:47
  • @Piro Oh I see what you're saying. The file is binary encoded. – mdornfe1 Dec 25 '17 at 07:12
  • Binary encoded via what protocol? – Yuval Itzchakov Dec 25 '17 at 07:14
  • @YuvalItzchakov It's a file from the bitcoin blockchain http://2.bp.blogspot.com/-DaJcdsyqQSs/UsiTXNHP-0I/AAAAAAAATC0/kiFRowh-J18/s1600/blockchain.png. – mdornfe1 Dec 25 '17 at 07:23
  • 2
    https://stackoverflow.com/questions/7619058/convert-a-byte-array-to-integer-in-java-and-vice-versa. – Alexey Romanov Dec 25 '17 at 07:35

1 Answers1

1
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.

Levi Ramsey
  • 18,884
  • 1
  • 16
  • 30