Java - Number byteValue() 方法



Java 的 Number byteValue() 方法將指定數字的值轉換為其對應的位元組值。這裡,我們稱之為“數字”,因為它可以是任何形式:int、long、float、double。

在我們進一步瞭解此方法之前,讓我們首先了解位元組的概念。

位元組定義為計算機基本使用的單位資料。這部分資料由八個二進位制數字(或位)組成,用於表示各種字元,例如數字、字母或符號。有些計算機使用 4 個位元組構成一個字,而有些計算機可以使用 2 個位元組或 1 個位元組。

它表示為“B”,範圍從 -128 到 127(包括)。

注意 - 此轉換可能涉及給定數字的舍入或截斷。

語法

以下是 Java Number byteValue() 方法的語法:

public byte byteValue()

引數

此方法不接受任何引數。

返回值

此方法在轉換後返回位元組值。

從 Integer 獲取位元組示例

以下示例顯示了 Java Number byteValue() 方法的使用。這裡我們建立了一個 Integer 物件,然後嘗試使用該方法將其轉換為其位元組值。

public class NumberByteVal {
   public static void main(String[] args) {
   
      // Assign an input value to Integer class
      Integer x = new Integer(134);
	  
      // Print their value as byte
      System.out.println("x as integer: " + x + ", x as byte: " + x.byteValue());
	  
   }
 }

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

x as integer: 134, x as byte: -122

從 Long 獲取位元組示例

在下面的示例中,我們正在建立 Long 類的物件,並在其上呼叫 byteValue() 方法。然後,long 值將轉換為其對應的位元組值。

public class NumberByteVal {

   public static void main(String[] args) {
   
      Long x = new Long(5632782);
      // Print their value as byte
      System.out.println("x as long: " + x + ", x as byte: " + x.byteValue());
   }
 }

輸出

編譯並執行上述程式後,輸出將顯示如下:

x as long: 5632782, x as byte: 14

從 Float 獲取位元組示例

下面的程式將浮點值賦給 Float 類引用變數,並在其上呼叫給定方法以將其浮點值轉換為位元組值。

public class NumberByteVal {
   public static void main(String[] args) {
   
      Float x = 9876f;
      // Print their value as byte
      System.out.println("x as float: " + x  + ", x as byte: " + x.byteValue());
   }
}

輸出

編譯並執行程式後,輸出將顯示如下:

x as float: 9876.0, x as byte: -108

從 Double 獲取位元組示例

以下示例將雙精度值賦給 Double 類引用,並呼叫 byteValue() 方法將雙精度值轉換為其位元組值。

public class NumberByteVal {
   public static void main(String[] args) {
   
      Double x = 3874d;
      // Print their value as byte
      System.out.println("x as double: " + x  + ", x as byte: " + x.byteValue());
   }
}

輸出

上述程式的輸出如下:

x as double: 3874.0, x as byte: 34
java_lang_number.htm
廣告
© . All rights reserved.