在Java中,byte类型是8位有符号数据类型,它的取值区间是Byte.MIN_VALUE
-128到Byte.MAX_VALUE
127(包含).
Java没有无符号字节类型(取值范围0-255)。我们可以把byte
转换为int
,在和0xff
进行位与运算来避免符号扩展。
1. 无符号byte类型
Java8中引入了一个新的接口Byte.toUnsignedInt()
用于转换有符号byte类型为无符号byte类型。
package com.mkyong;
public class JavaExample1 {
public static void main(String[] args) {
byte input = (byte) -2; // -2 (有符号) 254 (无符号)
System.out.println(input); // -2
System.out.println(convertBytesToUnsignedBytes(input)); // 254
// Java 8
System.out.println(Byte.toUnsignedInt(input)); // 254
}
public static int convertBytesToUnsignedBytes(Byte x) {
// 自动转换为int
return x & 0xFF;
// 显示转换为int
// return ((int) x) & 0xFF;
}
}
输出
-2
254
254
2. 解释
package com.mkyong;
public class JavaExample2 {
public static void main(String[] args) {
byte input = (byte) -2; // -2 (有符号) 254 (无符号)
// -2 = 1111 1110 , 2的补码形式
System.out.println("Input : " + input);
// byte转int会发生符号扩展
// 1111 1111 | 1111 1111 | 1111 1111 | 1111 1110
int input2 = (int) input;
System.out.println("Input [Binary] : " + Integer.toBinaryString(input2));
// 1111 1111 | 1111 1111 | 1111 1111 | 1111 1110
// &
// 0000 0000 | 0000 0000 | 0000 0000 | 1111 1111 (0xFF) , 获取最后8个bit
// =============================================
// 0000 0000 | 0000 0000 | 0000 0000 | 1111 1110 无符号byte
int result = input2 & 0xff;
System.out.println(result); // 254
System.out.println(Integer.toBinaryString(result)); // 1111 1110
// Java 8
System.out.println(Byte.toUnsignedInt(input));
}
}
输出
Input : -2
Input [Binary] : 11111111111111111111111111111110
254
11111110
254