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. :-)
Asked
Active
Viewed 589 times
2
-
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 Answers
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
-
Ahhh, that's the missing link - thanks. Of course, I need ByteOrder.LITTLE_ENDIAN. – Christian Schlichtherle Apr 04 '12 at 14:03
-
1Okay, I probably need to write a decorator so that I can comfortably read and write unsigned integers. – Christian Schlichtherle Apr 04 '12 at 14:13