四个字节转无符号整型java,从2或4个字节转换为有符号/无符号short / int

I have to convert bytes to signed/unsigned int or short.

The methods below are correct? Which is signed and which unsigned?

Byte order: LITTLE_ENDIAN

public static int convertTwoBytesToInt1(byte b1, byte b2) {

return (int) ((b2 << 8) | (b1 & 0xFF));

}

VS.

public static int convertTwoBytesToInt2(byte b1, byte b2) {

return (int) (( (b2 & 0xFF) << 8) | (b1 & 0xFF));

}

and

public static int convertFourBytesToInt1(byte b1, byte b2, byte b3, byte b4){

return (int) ((b4<<24)+(b3<<16)+(b2<<8)+b1);

}

VS.

public static int convertFourBytesToInt2(byte b1, byte b2, byte b3, byte b4){

return (int) (( (b4 & 0xFF) << 24) | ((b3 & 0xFF) << 16) | ((b2 & 0xFF) << 8) | (b1 & 0xFF));

}

I'm interested only in this conversion forms. Thanks!

解决方案

The first method (convertXXXToInt1()) of each pair is signed, the second (convertXXXToInt2()) is unsigned.

However, Java int is always signed, so if the highest bit of b4 is set, the result of convertFourBytesToInt2() will be negative, even though this is supposed to be the "unsigned" version.

Suppose a byte value, b2 is -1, or 0xFF in hexadecimal. The << operator will cause it to be "promoted" to an int type with a value of -1, or 0xFFFFFFFF. After the shift of 8 bits, it will be 0xFFFFFF00, and after a shift of 24 bytes, it will be 0xFF000000.

However, if you apply the bitwise & operator, the higher-order bits will be set to zero. This discards the sign information. Here are the first steps of the two cases, worked out in more detail.

Signed:

byte b2 = -1; // 0xFF

int i2 = b2; // 0xFFFFFFFF

int n = i2 << 8; // 0x0xFFFFFF00

Unsigned:

byte b2 = -1; // 0xFF

int i2 = b2 & 0xFF; // 0x000000FF

int n = i2 << 8; // 0x0000FF00

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值