简体   繁体   中英

how to reverse the bytes inside the buffer using java

I have a buffer contains Two bytes lets imagine the buffer is: org.jboss.netty.buffer.ChannelBuffer buffer[28,29,30,31,32] to read the two fisrt bytes in java we use this function :

buffer.readShort()

but what i want to do is to read the buffer from 29 to 28(i want to reverse the order of the bytes).

Since this is not your objects, you will have to read the Byte yourself using readByte .

For a Short, create an array of Byte[2] and call the method twice to fill it :

byte[] shortByte = {
    channel.readByte(),
    channel.readByte()
}

Then reverse it or simpler

byte[] shortByte = new byte[2];
shortByte[1] = channel.readByte();
shortByte[0] = channel.readByte();

Then, from this, you just need to create the Short from this array. You can see how from the following post : Convert a byte array to integer in java and vice versa

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM