Reputation: 291
I have an existing protocol (unchangeable) that I am trying to implement with netty where the packets have bytes that have to be read in both big and little endian as well as responses written in big and little endian.
Example: 00 00 00 04 02 00 05 00 00 00
This packets values are 4, 2 and 5.
I know that I can implement this my own way, but I would like know if there is a "Netty" way to do this.
I have found the .order(ByteOrder) method but this appears to just make a new buffer and I don't see why I should have to create a new object to read bytes in a different order. Am i missing something here?
Upvotes: 1
Views: 2259
Reputation: 12351
You can simply leave the buffer's byte order as big-endian and use BufUtil.swap*()
. In your case:
int a = buf.readInt();
int b = BufUtil.swapShort(buf.readShort());
int c = BufUtil.swapInt(buf.readInt());
On the other hand, in Netty 4, the buffer created by .order(ByteOrder)
is cached by the original buffer, so the overhead of .order(ByteOrder)
should be pretty small as long as the connection is short-living. If you used .order(ByteOrder)
:
int a = buf.readInt();
int b = buf.order(LITTLE_ENDIAN).readShort();
int c = buf.order(LITTLE_ENDIAN).readInt();
I'm actually curious if using .order(..)
is noticeably slower than using BufUtil.swap*()
although my guess is they should be essentially almost same.
Upvotes: 2