Java byte到Int的转换
Java byte到Int的转换有两种:
byte本身是带正负符号的, 默认向上转换也是带符号
byte本身是带正负符号的, 默认向上转换也是带符号
byte b = -3;
int i = b;
System.out.println(i); // 结果是 -3
byte b = -3;
int i = (int)b;
System.out.println(i); // 结果是 -3
i = Byte.toUnsignedInt(b);
源码是
/**
* Converts the argument to an {@code int} by an unsigned
* conversion. In an unsigned conversion to an {@code int}, the
* high-order 24 bits of the {@code int} are zero and the
* low-order 8 bits are equal to the bits of the {@code byte} argument.
*
* Consequently, zero and positive {@code byte} values are mapped
* to a numerically equal {@code int} value and negative {@code
* byte} values are mapped to an {@code int} value equal to the
* input plus 28.
*
* @param x the value to convert to an unsigned {@code int}
* @return the argument converted to {@code int} by an unsigned
* conversion
* @since 1.8
*/
public static int toUnsignedInt(byte x) {
return ((int) x) & 0xff;
}
1.8版才有?
i = b&0xff;
或者
i = b&0xFF;
i = b&255;
if(b<0)i=b+256; else i=b;
i = b<0 ? b+256 : b;
if(b>=0)i=b; else i=b+256; //是大于等于 , 而不能是大于
i = b>=0 ? b : b+256; //是大于等于 , 而不能是大于
public class T2206040611 {
public static void main(String[] args) {
byte b = -3;
int i;
i = b; System.out.println(i);
i = (int)b; System.out.println(i);
i = Byte.toUnsignedInt(b); System.out.println(i);
i = b&0xff; System.out.println(i);
i = b&255; System.out.println(i);
if(b<0)i=b+256; else i=b; System.out.println(i);
i = b<0 ? b+256 : b; System.out.println(i);
}
}
结果
-3
-3
253
253
253
253
253
测试代码230601
package p230601;
public class Byte转int的方法230601 {
public static void main(String[] args) {
int i;
for(byte b : new byte[]{ -128, -64, -32, -16, -8, -4, -3, -2, -1, 0, 1, 2, 3, 4, 8, 16, 32, 64, 127 }){
i = b; p(i);
i = (int)b; p(i);
i = Byte.toUnsignedInt(b); p(i);
i = b&0xff; p(i);
i = b&255; p(i);
if(b<0)i=b+256; else i=b; p(i); //是小于< , 而不能是小于等于
i = b<0 ? b+256 : b; p(i); //是小于< , 而不能是小于等于
if(b>=0)i=b; else i=b+256; p(i); //是大于等于 , 而不能是大于
i = b>=0 ? b : b+256; p(i); //是大于等于 , 而不能是大于
System.out.println();
}
}
static void p(int i){
if(i==-128)System.out.print(""+i+"\t\t");
else System.out.print(""+i+"\t\t\t");
}
}
结果
-128 -128 128 128 128 128 128 128 128
-64 -64 192 192 192 192 192 192 192
-32 -32 224 224 224 224 224 224 224
-16 -16 240 240 240 240 240 240 240
-8 -8 248 248 248 248 248 248 248
-4 -4 252 252 252 252 252 252 252
-3 -3 253 253 253 253 253 253 253
-2 -2 254 254 254 254 254 254 254
-1 -1 255 255 255 255 255 255 255
0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2
3 3 3 3 3 3 3 3 3
4 4 4 4 4 4 4 4 4
8 8 8 8 8 8 8 8 8
16 16 16 16 16 16 16 16 16
32 32 32 32 32 32 32 32 32
64 64 64 64 64 64 64 64 64
127 127 127 127 127 127 127 127 127