Java Number类

Java Number byteValue() 方法将指定数字的值转换为其对应的字节值。在这里,我们所说的"数字"可以是任何形式:int、long、float、double。

在我们详细了解此方法之前,让我们首先了解字节的概念。

字节被定义为计算机基本使用的数据单位。该数据长度为八个二进制数字(或位),用于表示数字、字母或符号等各种字符。有些计算机需要 4 个字节来构成一个字,有些计算机可以需要 2 个字节或一个字节。

它表示为"B",范围为 -128 到 127(含)。

它表示为"B"。>

注意 - 此转换可能涉及给定数字的舍入或截断。

语法

以下是 Java Number byteValue() 的语法method -

public byte byteValue()

参数

该方法不接受任何参数。

返回值

该方法返回转换后的字节值.

示例

以下示例显示 Java Number byteValue() 方法的用法。这里我们创建了一个 Integer 对象,然后尝试使用方法将其转换为字节值。

public class NumberByteVal {
   public static void main(String[] args) {
   
      //将输入值分配给Integer类
      Integer x = new Integer(134);
	  
      // 将它们的值打印为字节
      System.out.println("x as integer: " + x + ", x as byte: " + x.byteValue());
	  
   }
 }

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

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

示例

在下面的示例中,我们创建 Long 类的对象,并在其上调用 byteValue() 方法。然后,长整型值将被转换为相应的字节值。

public class NumberByteVal {

   public static void main(String[] args) {
   
      Long x = new Long(5632782);
      // 将它们的值打印为字节
      System.out.println("x as long: " + x + ", x as byte: " + x.byteValue());
   }
 }

编译并执行上述程序时,输出将显示如下 -

x as long: 5632782, x as byte: 14

示例

以下程序将浮点值分配给 Float 类引用变量,并调用其给定方法将其浮点值转换为字节值。

public class NumberByteVal {
   public static void main(String[] args) {
   
      Float x = 9876f;
      // 将它们的值打印为字节
      System.out.println("x as float: " + x  + ", x as byte: " + x.byteValue());
   }
}

编译并执行程序后,输出显示如下 -

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

示例

以下示例将双精度值分配给 Double 类引用,并调用 byteValue() 方法将双精度值转换为其字节值。

public class NumberByteVal {
   public static void main(String[] args) {
   
      Double x = 3874d;
      // 将它们的值打印为字节
      System.out.println("x as double: " + x  + ", x as byte: " + x.byteValue());
   }
}

上述程序的输出如下 -

x as double: 3874.0, x as byte: 34