
本文介绍了在 Java 中将有符号字节数组转换为表示相应无符号值的整数数组的常用方法。由于 Java 中 byte 类型是有符号的,因此需要进行转换以获得无符号表示。本文将探讨使用循环的直接方法,并讨论避免转换的替代方案,例如使用 Byte.toUnsignedInt。
在 Java 中,byte 类型是有符号的,其范围是 -128 到 127。当需要将 byte 值视为无符号值(范围为 0 到 255)时,就需要进行转换。以下是如何将有符号字节数组转换为表示相应无符号值的整数数组的几种方法。
最直接的方法是使用循环遍历字节数组,并将每个 byte 值转换为其对应的无符号 int 值。
public class SignedBytesToUnsignedInts {
public static int[] convertBytesToUnsignedInts(byte[] signedBytes) {
int[] unsignedInts = new int[signedBytes.length];
for (int i = 0; i < signedBytes.length; i++) {
unsignedInts[i] = signedBytes[i] & 0xFF;
}
return unsignedInts;
}
public static void main(String[] args) {
byte[] signedBytes = {-128, -103, 0, 127};
int[] unsignedInts = convertBytesToUnsignedInts(signedBytes);
for (int unsignedInt : unsignedInts) {
System.out.println(unsignedInt);
}
}
}代码解释:
立即学习“Java免费学习笔记(深入)”;
convertBytesToUnsignedInts(byte[] signedBytes) 方法:
main(String[] args) 方法:
注意事项:
从 Java 8 开始,Byte 类提供了一个方便的 toUnsignedInt() 方法,可以直接将 byte 转换为无符号 int。
import java.util.Arrays;
public class SignedBytesToUnsignedInts {
public static int[] convertBytesToUnsignedInts(byte[] signedBytes) {
return Arrays.stream(signedBytes)
.mapToInt(Byte::toUnsignedInt)
.toArray();
}
public static void main(String[] args) {
byte[] signedBytes = {-128, -103, 0, 127};
int[] unsignedInts = convertBytesToUnsignedInts(signedBytes);
for (int unsignedInt : unsignedInts) {
System.out.println(unsignedInt);
}
}
}代码解释:
立即学习“Java免费学习笔记(深入)”;
convertBytesToUnsignedInts(byte[] signedBytes) 方法:
main(String[] args) 方法:
注意事项:
在某些情况下,可以避免完全转换字节数组。例如,如果只是想将单个字节视为无符号值,可以使用 Byte.toUnsignedInt() 方法或 & 0xFF 操作符直接进行操作。
public class SignedBytesToUnsignedInts {
public static void main(String[] args) {
byte signedByte = -128;
// 使用 Byte.toUnsignedInt()
int unsignedInt1 = Byte.toUnsignedInt(signedByte);
System.out.println("Byte.toUnsignedInt: " + unsignedInt1);
// 使用 & 0xFF
int unsignedInt2 = signedByte & 0xFF;
System.out.println("& 0xFF: " + unsignedInt2);
}
}代码解释:
立即学习“Java免费学习笔记(深入)”;
结论
将有符号字节数组转换为无符号整数数组有多种方法。选择哪种方法取决于具体的需求和 Java 版本。对于 Java 8 及以上版本,Byte.toUnsignedInt() 方法提供了一种简洁易读的方式。对于更早的版本,可以使用循环和按位与运算符。如果可能,尽量避免完全转换数组,而是直接将单个字节视为无符号值进行操作。
以上就是将有符号字节数组转换为无符号整数数组的 Java 方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号