简体   繁体   English

如何将String转换为byte

[英]How to convert String to byte

I am trying to convert the string to byte, but I become NumberFormatException . 我试图将字符串转换为字节,但我成为NumberFormatException

String s = "SYNC";
Byte b = Byte.valueOf(s);
System.out.println(b);
  String example = "This is an example";
  byte[] bytes = example.getBytes();

Try using .getBytes() 尝试使用.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. 如果您要查找的是给定字符串中的单个字符,则可能需要使用.charAt() (or you could simply convert byte to char using (char) ). (或者您可以使用(char)将字节转换为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. 更多内容正如文档所说,字符串中的字符必须都是十进制数字或者该参数被解释为表示带符号的十进制字节,因为java.lang.Byte的API说。

Returns a Byte object holding the value given by the specified String. 返回包含指定String给定值的Byte对象。 The argument is interpreted as representing a signed decimal byte, exactly as if the argument were given to the parseByte(java.lang.String) method. 该参数被解释为表示带符号的十进制字节,就像将参数赋予parseByte(java.lang.String)方法一样。 The result is a Byte object that represents the byte value specified by the string. 结果是一个Byte对象,表示字符串指定的字节值。

So do as below, 如下所示,

String s = "SYNC";
byte[] b = s.getBytes();

The number has to be within the byte range, otherwise a NumberFormatException will be thrown. 该数字必须在字节范围内,否则将抛出NumberFormatException。

 byte[] bytes = s.getBytes();

Try this: 尝试这个:

Byte in java has range [-128;127]. java中的字节具有范围[-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 ? 编码为ASCII char值的“SYNC”字符串值为83,89,78,67。您如何将4个值的序列转换为仅1个值?

Calls sequence: Byte.valueOf(str) => Byte.parseByte(str, 10) => Integer.parseInt(str, 10) 调用序列:Byte.valueOf(str)=> Byte.parseByte(str,10)=> Integer.parseInt(str,10)

  1. So, you try to use string as base 10 number. 因此,您尝试使用字符串作为基数10。 All characters in this string greater then 10 (max value for this base), so NumberFormatException will be thrown. 此字符串中的所有字符大于10(此基数的最大值),因此将抛出NumberFormatException。

  2. If all the characters in your string valid base 10 characters. 如果字符串中的所有字符都有效,则为10个字符。 Such as string "546", paseInt will finished correctly. 如字符串“546”,paseInt将正确完成。 But parseByte will check byte range [-127:128]. 但是parseByte会检查字节范围[-127:128]。 If value not in range NumberFormatException. 如果值不在NumberFormatException范围内。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM