Converting a String byte to byte
Hello,
I'm trying to convert a MAC address written in String to a byte array. I've started with the following code, just to try it out:
byte b = Byte.decode("0xFF").byteValue();
However, this gives me NumberFormatException (value out of range). Why is that?
you get the exception because the decode method allows only positive numbers, and 0xFF corresponds to the byte -1
if you use the Integer class instead of Byte, 0xFF corresponds to 255 so there won't be any problem..byte b = Integer.decode("0xFF").byteValue();
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Byte.html#MAX_VALUE
the maximum value a byte can have, 2^7-1. (i.e. 128-1 = 127)
0xFF=16^2-1=256-1=255 (i.e. >127)
If you want to convert String to byte array, why don't you use
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html#getBytes()
Because byte is signed, so it has the range [-128, 127]. That value is 255.You can use Integer.decode instead, then call byteValue, or call intValue and test to see if the value is in the range [0,255], if you're concerned about out-of-bounds data.