0

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);
2
  • What did you expect? Perhaps you wanted char Commented Feb 18, 2013 at 8:01
  • actually i want to convert this cpp statement into java info->CommandName = (unsigned char*)GetCommandName(cmd->CommandData[0]); here CommandName is char type and the method GetCommandName returns a string "SYNC"; Commented Feb 18, 2013 at 8:16

5 Answers 5

2
  String example = "This is an example";
  byte[] bytes = example.getBytes();
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

The number has to be within the byte range, otherwise a NumberFormatException will be thrown.

 byte[] bytes = s.getBytes();

Try this:

Comments

0

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();

Comments

0

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)

  1. 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.

  2. 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.