Java.lang.Byte 类

java.lang.Byte.decode() 方法用于将字符串解码为字节。接受由以下语法给出的十进制、十六进制和八进制数字:

DecodableString:

  • Signopt DecimalNumeral
  • 签名opt 0x HexDigits
  • 签名opt 0X HexDigits
  • 签名opt # 十六进制数字
  • 签名opt 0 八进制数字

签名:

  • +
  • -

可选符号和/或基数说明符("0x"、"0X"、"#"或前导)后面的字符序列零)由 Byte.parseByte 方法使用指定的基数(10、16 或 8)进行解析。该字符序列必须表示正值,否则将引发 NumberFormatException。如果指定字符串的第一个字符是减号,则结果取反。字符串中不允许有空格字符。

语法

public static Byte decode(String nm)
                   throws NumberFormatException

参数

nm 指定要解码的字符串。

返回值

返回保存 nm 表示的字节值的 Byte 对象。

异常

如果字符串不包含可解析字节,则抛出NumberFormatException

示例:

在下面的示例中,java.lang.Byte.decode()方法用于将字符串解码为字节。

import java.lang.*;

public class MyClass {
  public static void main(String[] args) {
    
    //创建一个保存字节值的字符串
    String x1 = "25";    //十进制数
    String x2 = "0x6f";  //十六进制数
    String x3 = "0X6B";  //十六进制数
    String x4 = "-#6c";  //十六进制数
    String x5 = "027";   //八进制数

    //创建字节对象
    Byte y1 = Byte.decode(x1);
    Byte y2 = Byte.decode(x2);
    Byte y3 = Byte.decode(x3);
    Byte y4 = Byte.decode(x4);
    Byte y5 = Byte.decode(x5);

    //打印Byte对象
    System.out.println("The Byte object y1 is: " + y1);
    System.out.println("The Byte object y2 is: " + y2);  
    System.out.println("The Byte object y3 is: " + y3);  
    System.out.println("The Byte object y4 is: " + y4);  
    System.out.println("The Byte object y5 is: " + y5);     
  }
}

输出上面的代码将是:

The Byte object y1 is: 25
The Byte object y2 is: 111
The Byte object y3 is: 107
The Byte object y4 is: -108
The Byte object y5 is: 23