Valeriy K.
Valeriy K.

Reputation: 2906

Convert from hex to int and vice versa in java

I have next method for converting to int from hex:

public static byte[] convertsHexStringToByteArray2(String hexString) {
    int hexLength = hexString.length() / 2;
    byte[] bytes = new byte[hexLength];
    for (int i = 0; i < hexLength; i++) {
        int hex = Integer.parseInt(hexString.substring(2 * i, 2 * i + 2), 16);
        bytes[i] = (byte) hex;
    }

    return bytes;
}

when I use it for "80" hex string I get strange, not expected result:

public static void main(String[] args) {
    System.out.println(Arrays.toString(convertsHexStringToByteArray2("80"))); // gives -128
    System.out.println(Integer.toHexString(-128));
    System.out.println(Integer.toHexString(128));
}

the output:

[-128]
ffffff80
80

I expect that "80" will be 128. What is wrong with my method?

Upvotes: 1

Views: 205

Answers (2)

Clijsters
Clijsters

Reputation: 4256

I have next method for converting to int from hex

The method you posted converts a hex String to a byte array, and not to an int. That's why it is messing with its sign.

Converting from hex to int is easy:

Integer.parseInt("80", 16)
$1 ==> 128

But if you want to get a byte array for further processing by just casting:

(byte) Integer.parseInt("80", 16)
$2 ==> -128

It "changes" its sign. For further information on primitives and signed variable types take a look at Primitive Data Types, where it says:

The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation.

One could easily invert the sign by just increasing the value to convert:

(byte) Integer.parseInt("80", 16) & 0xFF
$3 ==> 128

That gets you a byte with the value you expect. Technically that result isn't correct and you must to switch the sign again, if you want to get an int or a hex string back again. I'd suggest you to don't use a byte array if you only want to convert between hex and dec.

Upvotes: 1

Tom
Tom

Reputation: 394

A byte in Java stores numbers from -128 to 127. 80 in hex is 128 as an integer, which is too large to be stored in a byte. So, the value wraps around. Use a different type to store your value (such as a short).

Upvotes: 0

Related Questions