2

I need to read and write signed and unsigned integers with a SeekableByteChannel in little endian format. This may seem silly, but I cannot find something in the JDK. Have I missed something or am I expected to roll this on my own? This would be no problem, but I don't feel like reinventing the wheel today. :-)

Christian Schlichtherle
  • 3,125
  • 1
  • 23
  • 47
  • Do you have any code at all? I don't see anything called SeekableByteChannel in the JDK, the nearest thing I can see to that in the nio package is WritableByteChannel. – Jon Apr 04 '12 at 14:02
  • This is java.nio.channels.SeekableByteChannel in JSE 7. – Christian Schlichtherle Apr 04 '12 at 14:04
  • Ah, I see it now. Sorry, thought I looked through 6 and 7, but actually just looked through 6 twice.. – Jon Apr 04 '12 at 14:21

1 Answers1

2

Sounds like a work for the ByteBuffer.

Somewhat like

public static void main(String[] args) {
    byte[] payload = toArray(-1991249);
    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();
}
Edwin Dalorzo
  • 76,803
  • 25
  • 144
  • 205