简体   繁体   中英

Convert two unsigned bytes to an int in Java

So let's say I've got two unsigned bytes coming from a device to my software:

And I can read their value by:

int first = buffer[0] & 0xFF;
int second = buffer[1] & 0xFF;

And then how can convert these two numbers into an int in Java?

In short: convert unsigned byte buffer array into an int

More details:

So let's say if I have a signed byte array, I can convert it to an int by this way:

int val = ((bytes[0] & 0xff) << 8) | (bytes[1] & 0xff);

but then what should I do to convert an unsigned byte array to an int?

// UPDATED:

Just figured out the way to convert it:

private int toInt(byte[] b) {
    int x = (0 << 24) | (0 << 16)
            | ((b[1] & 0xFF) << 8) | ((b[0] & 0xFF) << 0);
    return x;
}

I don't know whether this is what you want, but you can do it this way:

    int b1 = ...; // first byte
    int b2 = ...; // second byte
    String binaryString = pad0s(Integer.toBinaryString(b1), 8) + pad0s(Integer.toBinaryString(b2), 8);
    System.out.println(Integer.valueOf(binaryString, 2));

Where pad0s is defined as:

private static String pad0s(String str, int length) {
    if (str.length() >= length) return str;
    int diff = length - str.length();
    StringBuilder sb = new StringBuilder(str);
    for (int i = 0 ; i < diff ; i++) {
        sb.insert(0, "0");
    }
    return sb.toString();
}

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