从2或4个字节转换为有符号

从2或4个字节转换为有符号

本文介绍了从2或4个字节转换为有符号/无符号short / int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须将字节转换为signed / unsigned int或short。

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

以下方法是否正确?哪个是签名的,哪个是未签名的?

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

字节顺序:LITTLE_ENDIAN

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));
}

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!

推荐答案

第一种方法( convertXXXToInt1())对被签名,第二个( convertXXXToInt2())是无符号的。

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

但是,Java int 始终是有符号的,因此如果设置了 b4 的最高位,则 convertFourBytesToInt2()的结果将为负数,即使这应该是未签名版本。

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.

假设字节 value, b2 为-1,或十六进制为0xFF。 << 运算符将使其提升为 int 类型,值为-1 ,或0xFFFFFFFF。在8位移位后,它将为0xFFFFFF00,在移位24字节后,它将为0xFF000000。

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.

签名:

byte b2 = -1; // 0xFF
int i2 = b2; // 0xFFFFFFFF
int n = i2 << 8; // 0x0xFFFFFF00

未签名:

byte b2 = -1; // 0xFF
int i2 = b2 & 0xFF; // 0x000000FF
int n = i2 << 8; // 0x0000FF00

这篇关于从2或4个字节转换为有符号/无符号short / int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 12:57