Important Notice: Our web hosting provider recently started charging us for additional visits, which was unexpected. In response, we're seeking donations. Depending on the situation, we may explore different monetization options for our Community and Expert Contributors. It's crucial to provide more returns for their expertise and offer more Expert Validated Answers or AI Validated Answers. Learn more about our hosting issue here.

How can I read or write binary files written in little-endian format?

0
Posted

How can I read or write binary files written in little-endian format?

0

Location: http://www.jguru.com/faq/view.jsp?EID=205923 Created: Sep 14, 2000 Modified: 2000-10-14 10:57:16.689 Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question originally posed by man sung jun (http://www.jguru.com/guru/viewbio.jsp?EID=200638 In order to read multi-byte values, where you know the byte order is not in the Java standard big-endian format, you basically need to read the individual bytes yourself and rearrange them. For instance, the following will read in a 4 byte int and swap the byte order around. // read four bytes int b1 = is.read(); int b2 = is.read(); int b3 = is.read(); int b4 = is.read(); // combine them int combined = (b4 && 0xFF) << 24 + (b3 && 0xFF) << 16 + (b2 && 0xFF) << 8) + (b1 && 0xFF); When working with floating point numbers, the Float.floatToIntBits() and Float.intBitsToFloat() methods may prove helpful. Writing is just doing things in the opposite order, splitting apart the int first, then writing the individual pieces.

Related Questions

What is your question?

*Sadly, we had to bring back ads too. Hopefully more targeted.

Experts123