在Java中使用显式转换将长值转换为字节
在Java中,一个字节只能包含从 -128 到 127 的值,如果我们尝试将 long 值转换为高于或低于该字节的限制,那么精度将有所损失。
1.字节:字节数据类型是一个 8 位有符号二进制补码整数。
句法:
byte varName; // Default value 0
价值观:
1 byte (8 bits) :
-128 to 127
2. long: long 数据类型为64 位二进制补码整数。
句法:
long varName; // Default value 0
价值观:
8 byte (64 bits):
-9223372036854775808 to 9223372036854775807
示例 1:在限制中
Java
// Java Program to Convert Long (under Byte limit)
// Values into Byte using explicit casting
import java.io.*;
class GFG {
public static void main(String[] args)
{
long firstLong = 45;
long secondLong = -90;
// explicit type conversion from long to byte
byte firstByte = (byte)firstLong;
byte secondByte = (byte)secondLong;
// printing typecasted value
System.out.println(firstByte);
System.out.println(secondByte);
}
}
Java
// Java Program to Convert Long (out of the
// limits of Byte) Values into Byte using
// explicit casting
import java.io.*;
class GFG {
public static void main(String[] args)
{
long firstLong = 150;
long secondLong = -130;
// explicit type conversion from long to byte
byte firstByte = (byte)firstLong;
byte secondByte = (byte)secondLong;
// printing typecasted value
System.out.println(firstByte);
System.out.println(secondByte);
}
}
输出
45
-90
示例 2:超出限制
Java
// Java Program to Convert Long (out of the
// limits of Byte) Values into Byte using
// explicit casting
import java.io.*;
class GFG {
public static void main(String[] args)
{
long firstLong = 150;
long secondLong = -130;
// explicit type conversion from long to byte
byte firstByte = (byte)firstLong;
byte secondByte = (byte)secondLong;
// printing typecasted value
System.out.println(firstByte);
System.out.println(secondByte);
}
}
输出
-106
126