Java EndianUtils-class And Method Code Example
Here's an example of how to use the EndianUtils class from the org.apache.commons.io package in Java to read and write values in different endian formats:
import org.apache.commons.io.EndianUtils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
byte[] data = {0x12, 0x34, 0x56, 0x78};
ByteArrayInputStream bais = new ByteArrayInputStream(data);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
// Read a big-endian int from the input stream
int value = EndianUtils.readSwappedInteger(bais);
System.out.println("Read big-endian int: " + value);
// Write a little-endian int to the output stream
EndianUtils.writeSwappedInteger(baos, value);
byte[] result = baos.toByteArray();
System.out.println("Wrote little-endian int: " + EndianUtils.readSwappedInteger(new ByteArrayInputStream(result)));
} catch (IOException e) {
e.printStackTrace();
}
}
}
This example shows how to use the readSwappedInteger() method from the EndianUtils class to read a big-endian int from an input stream and the writeSwappedInteger() method to write a little-endian int to an output stream. The example uses ByteArrayInputStream and ByteArrayOutputStream classes as input and output streams, but you can use other types of streams as well.
It's important to note that EndianUtils is deprecated as of commons-io 2.6, you can use DataInputStream and DataOutputStream instead which offers more functionality than EndianUtils.