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
廣告