从 2 或 4 个字节转换为有符号/无符号短/整数



我必须将字节转换为有符号/无符号的int或short。

下面的方法正确吗?哪个是签名的,哪个是未签名的?

字节顺序:LITTLE_ENDIAN

public static int convertTwoBytesToInt1(byte b1, byte b2) {
    return (int) ((b2 << 8) | (b1 & 0xFF));
}

与。

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

与。

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

对这种转换形式感兴趣。谢谢!

每对的第一个方法(convertXXXToInt1())是有符号的,第二个方法(convertXXXToInt2())是无符号的。

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

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

但是,如果应用按位&运算符,则高阶位将设置为零。这将丢弃符号信息。以下是这两个案例的第一步,更详细地制定出来。

签署:

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

4 字节无符号转换存在问题,因为它不适合 int。下面的例程工作正常。

public class IntegerConversion
{
  public static int convertTwoBytesToInt1 (byte b1, byte b2)      // signed
  {
    return (b2 << 8) | (b1 & 0xFF);
  }
  public static int convertFourBytesToInt1 (byte b1, byte b2, byte b3, byte b4)
  {
    return (b4 << 24) | (b3 & 0xFF) << 16 | (b2 & 0xFF) << 8 | (b1 & 0xFF);
  }
  public static int convertTwoBytesToInt2 (byte b1, byte b2)      // unsigned
  {
    return (b2 & 0xFF) << 8 | (b1 & 0xFF);
  }
  public static long convertFourBytesToInt2 (byte b1, byte b2, byte b3, byte b4)
  {
    return (long) (b4 & 0xFF) << 24 | (b3 & 0xFF) << 16 | (b2 & 0xFF) << 8 | (b1 & 0xFF);
  }
  public static void main (String[] args)
  {
    byte b1 = (byte) 0xFF;
    byte b2 = (byte) 0xFF;
    byte b3 = (byte) 0xFF;
    byte b4 = (byte) 0xFF;
    System.out.printf ("%,14d%n", convertTwoBytesToInt1 (b1, b2));
    System.out.printf ("%,14d%n", convertTwoBytesToInt2 (b1, b2));
    System.out.printf ("%,14d%n", convertFourBytesToInt1 (b1, b2, b3, b4));
    System.out.printf ("%,14d%n", convertFourBytesToInt2 (b1, b2, b3, b4));
  }
}

最新更新