Java - Byte decode() 方法



描述

Java Byte decode(String nm) 方法将字符串解码为 Byte。接受十进制、十六进制和八进制数字,其语法如下:

可解码字符串

  • Signopt DecimalNumeral
  • Signopt 0x HexDigits
  • Signopt 0X HexDigits
  • Signopt # HexDigits
  • Signopt 0 OctalDigits

Sign

  • +

在可选符号和/或基数说明符(“0x”、“0X”、“#”或前导零)之后出现的字符序列,将根据 Byte.parseByte 方法使用指示的基数 (10、16 或 8) 进行解析。

此字符序列必须表示正值,否则将抛出 NumberFormatException。如果指定字符串的第一个字符是减号,则结果将取反。字符串中不允许出现空格字符。

声明

以下是 java.lang.Byte.decode() 方法的声明

public static Byte decode(String nm)throws NumberFormatException

参数

nm − 要解码的字符串

返回值

此方法返回一个 Byte 对象,其中包含 nm 表示的字节值。

异常

NumberFormatException − 如果字符串不包含可解析的字节

将包含十进制值的字符串解码为 Byte 的示例

以下示例演示了使用 Byte decode() 方法和 Byte 对象的情况。这里我们创建了一个 Byte 变量,并使用 decode 方法将十进制字符串解码为字节,然后打印结果。

package com.tutorialspoint;

public class ByteDemo {
   public static void main(String[] args) {

      // create a Byte objects
      Byte b1;

      /**
       *  static methods are called using class name. 
       *  decimal value is decoded and assigned to Byte object b1
       */
      b1 = Byte.decode("100");

      // print value
      System.out.println( "Byte value of decimal 100 is " + b1 );
   }
}

输出

让我们编译并运行上述程序,这将产生以下结果:

Byte value of decimal 100 is 100

将包含十六进制值的字符串解码为 Byte 的示例

以下示例演示了使用 Byte decode() 方法和 Byte 对象的情况。这里我们创建了一个 Byte 变量,并使用 decode 方法将十六进制字符串解码为字节,然后打印结果。

package com.tutorialspoint;

public class ByteDemo {
   public static void main(String[] args) {

      // create a Byte objects
      Byte b1;

      /**
       *  static methods are called using class name. 
       *  hexadecimal value is decoded and assigned to Byte object b1
       */
      b1 = Byte.decode("0x6b");

      // print value
      System.out.println( "Byte value of hexadecimal 6b is " + b1 );
   }
}

输出

让我们编译并运行上述程序,这将产生以下结果:

Byte value of hexadecimal 6b is 107

将包含八进制值的字符串解码为 Byte 的示例

以下示例演示了使用 Byte decode() 方法和 Byte 对象的情况。这里我们创建了一个 Byte 变量,并使用 decode 方法将八进制字符串解码为字节,然后打印结果。

package com.tutorialspoint;

public class ByteDemo {
   public static void main(String[] args) {

      // create a Byte objects
      Byte b1;

      /**
       *  static methods are called using class name. 
       *  octal value is decoded and assigned to Byte object b1
       */
      b1 = Byte.decode("0127");

      // print value
      System.out.println( "Byte value of octal 127 is " + b1 );
   }
}

输出

让我们编译并运行上述程序,这将产生以下结果:

Byte value of octal 127 is 87
java_lang_byte.htm
广告
© . All rights reserved.