简体   繁体   中英

Integer.parseInt(string, radix) in Java returns (mostly) negative decimal values

As I said above I am using Integer.parseInt to convert hex values into decimal but I keep getting returned negative integers when I put in positive hex values:

byte[] bytes2 = getMacBytes("90:e6:ba:97:4a:bb");

private static byte[] getMacBytes(String macStr) throws IllegalArgumentException {
    byte[] bytes = new byte[6];
    String[] hex = macStr.split("(\\:|\\-)");
    for (int i = 0; i < 6; i++){
        System.out.println(hex[i]);
    }
    if (hex.length != 6) {
        throw new IllegalArgumentException("Invalid MAC address.");
    }
    try {
        for (int i = 0; i < 6; i++) {
            bytes[i] = (byte) Integer.parseInt(hex[i], 16);
            System.out.println(bytes[i]);
        }
    }
    catch (NumberFormatException e) {
        throw new IllegalArgumentException("Invalid hex digit in MAC address.");
    }
    return bytes;
}

when I run this code it returns this:

90 e6 ba 97 4a bb -112 -26 -70 -105 74 -69

So I can see the MAC address is being split properly, but 5 of the 6 hex values are being returned from Integer.parseInt(string, radix) as negative. I can see that the negative values are x + 256 of their actual decimal value but the second last is the correct decimal value... Any ideas why it is turning 5 of the 6 values into negatives?

I think parseInt is behaving correctly, but your cast to byte converts the numbers to the range [-128; 127]. Try storing the results in a short or int array, or keep them in a byte array, but remember to print them with System.out.println(bytes[i] & 0xff) .

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