Java byte到Int的转换
Java byte到Int的转换有两种:
- 带符号转换,数值转换
- 无符号转换
byte本身是带正负符号的, 默认向上转换也是带符号
带符号转换
byte本身是带正负符号的, 默认向上转换也是带符号
方法1 默认转换
byte b = -3;
int i = b;
System.out.println(i); // 结果是 -3
方法2 强制转换
byte b = -3;
int i = (int)b;
System.out.println(i); // 结果是 -3
无符号转换
方法1 i = Byte.toUnsignedInt(b);
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 2<sup>8</sup>.
*
* @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版才有? ?
方法2 i = b&0xff;
i = b&0xff;
或者
i = b&0xFF;
方法3 i = b&255;
i = b&255;
方法4 if(b<0)i=b+256; else i=b;
if(b<0)i=b+256; else i=b;
方法5 i = b<0 ? b+256 : b;
i = b<0 ? b+256 : b;
测试代码1
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
版权声明:本文为kfepiza原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。