0

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).

ItamarG3
  • 4,092
  • 6
  • 31
  • 44
  • 2
    please provide a [mcve] of you code, so that we can see the problem – ItamarG3 May 19 '17 at 11:25
  • take a look above, the post is updated –  May 19 '17 at 11:29
  • If readShort is reading from the `currentIndex` to `currentIndex + short.length`, just reverse the loop to read from `currentIndex + short.length` to `currentIndex` (and decremente the index used) – AxelH May 19 '17 at 11:31
  • @YoussefAssnai filling more numbers to the buffer is not shedding any light on your question ;) What class is `buffer`? Bow do you initialize it? How do you read from it? – lupz May 19 '17 at 11:32
  • how to do that?? is there java built function can do that?? –  May 19 '17 at 11:33
  • @YoussefAssnai without the code, I don't know, what is `buffer`, is it from an API ? If so, what is it returning, a `Byte[]` ? – AxelH May 19 '17 at 11:37
  • take a look above :buffer is an instance of ChannelBuffer its a java object –  May 19 '17 at 11:39
  • You mean `org.jboss.netty.buffer.ChannelBuffer` ? – AxelH May 19 '17 at 11:40
  • AxelH exactly..yess thats what i meant –  May 19 '17 at 11:42
  • you have any solution for me please?? –  May 19 '17 at 11:42
  • if you need any information i can provide it just ask –  May 19 '17 at 11:43
  • Finally.... you should have told that. We can't guess it. And stop spamming, edit the comments ;) – AxelH May 19 '17 at 11:43
  • so...is there any solution please?? –  May 19 '17 at 11:45
  • Use [this](https://docs.jboss.org/netty/3.2/api/org/jboss/netty/buffer/ChannelBuffer.html) as a reference and use either big endian or little endian HeapBuffer according to your need to change the byte order. hope this will help. – Avinash L May 19 '17 at 11:46

1 Answers1

1

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

Community
  • 1
  • 1
AxelH
  • 14,325
  • 2
  • 25
  • 55