Search code examples
javabyteushortulong

Converting raw-byte values into Java types


I have a problem with converting raw-bytes values into java types. I am receiving bytes by a datagram socket as a bytes array. I know exactly which bytes means what, but I don't know how to convert them appropriately (I mean I know offsets, but don't know if what I think I received is correct ;)).

For example, I want to convert 16 bit unsigned short into java int type. I found some examples in the web, the one is:

public int getUShort(byte[] bytes, int offset) {
    int b0 = bytes[offset] & oxFF;
    int b1 = bytes[offset + 1] & oxFF;

    return (b1 << 8) + (b0 << 0);

Another one is the same but the last line is:

return (b0 << 8)  + b1;

Of course it gives different results. Which one is correct? Can you please give me also a valid example how to do the same but for an unsigned long?

Thank you in advance!


Solution

  • You can use DataInputStream or ByteBuffer to read the various types. You can use signed types as unsigned values for most operations just the same. I have written a simple class to illustrate how you can use the signed types as if they were unsigned Unsigned

    ByteBuffer b = ByteBuffer.wrap(bytes);
    short s = b.getShort();
    long l = b.getLong();