Nayana
Nayana

Reputation: 1549

Convert an int to byte in java

String boxVal = "FB";
Integer val = Integer.parseInt(boxVal, 16);
System.out.println(val); //prints out 251
byte sboxValue = (byte) val;
System.out.println("sboxValue = " + Integer.toHexString(sboxValue)); //fffffffb

The last line should print out "fb". I am not sure why it prints out "fffffffb." What am I doing wrong? How should I fix my code to print "fb"?

Upvotes: 0

Views: 7901

Answers (2)

Henry
Henry

Reputation: 43798

Why does it print "fffffffb": because you first convert the byte value (which is -5) to an integer with value -5 and then print that integer.

The easiest way to get the output you want is:

System.out.printf("sboxValue = %02x\n", sboxValue);

Or, you could also use:

System.out.println("sboxValue = " + Integer.toHexString(sboxValue & 0xff));

What happens here in detail:

the byte value fb is converted to an integer. Since the value is negative, as you can see because the leftmost bit is 1, it is sign extended to 32 bits: fffffffb.

By masking out the lower 8 bits (with the bitwise and operation &) we get the integer value 000000fb.

Upvotes: 1

boskop
boskop

Reputation: 619

You have an overflow when you convert 251 to a byte. Byte has a minimum value of -128 and a maximum value of 127 (inclusive)

See here: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

Upvotes: 2

Related Questions