I’m having an issue with reading a Long variable from a binary file in Java.

My code:

Static long extractLong (DataInputStream dis) throw IOException{ byte[] bytes = new byte[8]; dis.read(bytes); ByteBuffer byteBuffer = ByteBuffer.wrap(byte); byteBuffer.order(ByteOrder.LITTLE_ENDIAN); return byteBuffer.getLong()  }

I know the variable should be 20577

And I’m getting 88377542049792

These number make more sense when you see what they are in Hex

20577 = 5061
88377542049792 = 506100000000

If I don’t change the order (endianness) I get 61500000hex as my input.

By changing the order it seems I’m only swapping the front two bytes.

I'm sure I'm making a mistake, this is my first project working directly with a binary file

Basil Bourque's user avatar

Basil Bourque

349k130 gold badges956 silver badges1.3k bronze badges

Haydn's user avatar

New contributor

Haydn is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

6

I have a suspicion that you don't need to read long, but int:

byte[] bytes = {0, 0, 0x50, 0x61, 0, 0, 0, 0}; ByteBuffer byteBuffer = ByteBuffer.wrap(bytes); System.out.println(byteBuffer.getLong()); // 88377542049792 byteBuffer.position(0); System.out.println(byteBuffer.getInt()); // 20577

Konstantin Makarov's user avatar

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.