I am trying to convert the string to byte, but I become NumberFormatException.
String s = "SYNC";
Byte b = Byte.valueOf(s);
System.out.println(b);
Try using .getBytes()
String s = "SYNC";
byte[] lst = s.getBytes();
for(byte b : lst ){
System.out.println(b);
}
If what you are looking for is a single character from given string, you might want to use .charAt() instead. (or you could simply convert byte to char using (char) ).
System.out.println(s.charAt(0)); //Prints first character from given string
A string can only be converted into a sequence of bytes.
More over as the doc says the The characters in the string must all be decimal digits or The argument is interpreted as representing a signed decimal byte as the API of java.lang.Byte says.
Returns a Byte object holding the value given by the specified String. The argument is interpreted as representing a signed decimal byte, exactly as if the argument were given to the parseByte(java.lang.String) method. The result is a Byte object that represents the byte value specified by the string.
So do as below,
String s = "SYNC";
byte[] b = s.getBytes();
Byte in java has range [-128;127]. The "SYNC" string encoded as ASCII char values 83, 89, 78, 67. How do you wan't to convert a sequence of 4 values to just 1 value ?
Calls sequence: Byte.valueOf(str) => Byte.parseByte(str, 10) => Integer.parseInt(str, 10)
So, you try to use string as base 10 number. All characters in this string greater then 10 (max value for this base), so NumberFormatException will be thrown.
If all the characters in your string valid base 10 characters. Such as string "546", paseInt will finished correctly. But parseByte will check byte range [-127:128]. If value not in range NumberFormatException.
char