Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store unsigned short in java?

So generally I'm using Netty and it's BigEndianHeapChannelBuffer to receive unsinged short (from c++ software) in Java. When I do it like this:

buf.readUnsignedByte(); buf.readUnsignedByte();

it returns: 149 and 00. Till now everything is fine. Because server sent 149 as unsigned short [2 bytes].

Instead of this I would like to receive unsigned short (ofc after restarting my application):

buf.readUnsignedShort();

and magic happens. It returns: 38144.

Next step is to retrieve unsigned byte: short type = buf.readUnsignedByte(); System.out.println(type);

and it returns: 1 which is correct output.

Could anyone help me with this? I looked deeper and this is what netty does with it:

public short readShort() {
    checkReadableBytes(2);
    short v = getShort(readerIndex);
    readerIndex += 2;
    return v;
}

public int readUnsignedShort() {
    return readShort() & 0xFFFF;
}

But still I can't figure what is wrong. I would like just be able to read that 149.

like image 651
mic-kul Avatar asked May 25 '26 21:05

mic-kul


1 Answers

You could also borrow a page from the Java DataInputStream.readUnsignedShort() implementation:

public final int readUnsignedShort() throws IOException {
    int ch1 = in.read();
    int ch2 = in.read();
    if ((ch1 | ch2) < 0)
        throw new EOFException();
    return (ch1 << 8) + (ch2 << 0);
}
like image 184
Nicholas Avatar answered May 27 '26 12:05

Nicholas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!