Java Data Type How to - Read and write integers with a SeekableByteChannel in little endian format








Question

We would like to know how to read and write integers with a SeekableByteChannel in little endian format.

Answer

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
/*  w  w  w . j  ava2  s. co m*/
public class Main {
  public static void main(String[] args) {
    byte[] payload = toArray(-1231232);
    int number = fromArray(payload);
    System.out.println(number);
  }

  public static int fromArray(byte[] payload) {
    ByteBuffer buffer = ByteBuffer.wrap(payload);
    buffer.order(ByteOrder.LITTLE_ENDIAN);
    return buffer.getInt();
  }

  public static byte[] toArray(int value) {
    ByteBuffer buffer = ByteBuffer.allocate(4);
    buffer.order(ByteOrder.LITTLE_ENDIAN);
    buffer.putInt(value);
    return buffer.array();
  }
}

The code above generates the following result.