Search code examples
javaarraystype-conversionintegerunsigned-integer

How to convert a uint16 stored as a little endian byte array to an int?


I'm receiving some data that is a little endian byte array that represents a uint16 but I want to store this in an int. I have wrapped this data into a ByteBuffer so I can call ByteBuffer.get() to get the next byte(s), but I am not sure how to convert these 2 bytes from uint16 to int.

    byte[] data = //From UDP socket
    ByteBuffer bb = ByteBuffer.wrap(data);
    bb = bb.order(ByteOrder.LITTLE_ENDIAN);
    while(bb.hasRemaining()){
        int n = //What goes here?
    }

Thanks for any help :)


Solution

  • The main complexity is in my opinion how to represent a uint16 in Java. I'd suggest to use Java int or Java long, because the least 16 bits have the same meaning as in uint16 (but not Java short: it has 16 bits, but is signed).

    1) If you receive uint16 only, no chars, no other types, then the easiest would be following. Read 16 bits into a Java short, then convert it to int:

    byte[] data = //From UDP socket
    ByteBuffer bb = ByteBuffer.wrap(data);
    bb = bb.order(ByteOrder.LITTLE_ENDIAN);
    
    while(bb.hasRemaining()){
        short s = bb.getShort();
        int n = 0xFFFF & s;
        ...
    }
    

    2) If you receive not only uint16, but some other types like chars, then you can construct the value from 2 bytes:

    byte[] data = //From UDP socket
    ByteBuffer bb = ByteBuffer.wrap(data);
    
    while(bb.hasRemaining()) {
        if (consider next bytes as uint16) {
            byte b1 = bb.get();
            byte b2 = bb.get();
            int i1 = 0xFF & b1; // Consider b1 as int, not the same as "(int) b1"
            int i2 = 0xFF & b2; // Consider b2 as int, not the same as "(int) b2"
            int n = b2 * 256 + b1;
            ...
        } else {
            // Read next bytes as char or something other
        }
    }