Java byte Array 到 signed Int

Java byte Array to signed Int

我正在尝试将带符号的 int 变量转换为 3 字节数组并向后转换。

在函数 getColorint 中,我将 int 值转换为字节数组。效果不错!

    public byte [] getColorByte(int color1){
    byte[] color = new byte[3];
    color[2] = (byte) (color1 & 0xFF);
    color[1] = (byte) ((color1 >> 8) & 0xFF);
    color[0] = (byte) ((color1 >> 16) & 0xFF);
    return color;
    }

但是如果我尝试使用 getColorint 函数将字节数组转换回整数:

    public int getColorint(byte [] color){
    int answer = color [2];
    answer += color [1] << 8;
    answer += color [0] << 16;
    return answer;
    }

它只适用于正整数值。

这是调试过程中的截图:

我的输入 int 值是 -16673281 但我的输出 int 值是 38143.

谁能帮帮我?

谢谢:)

Color class 定义了创建和转换颜色整数的方法。颜色表示为压缩整数,由 4 个字节组成:alpha、红色、绿色、蓝色。 你应该使用它。

这里的问题是字节被签名了。当您使用 color[2] == -1 执行 int answer = color[2] 时,答案也将是 -1,即 0xffffffff,而您希望它是 255 (0xff)。您可以使用 Guava 的 UnsignedBytes 作为补救措施,或者简单地使用 color[i] & 0xff 将其转换为 int.

由于颜色以 4 个字节表示,因此您还应该存储一个 alpha 通道。

来自 Int :

public byte [] getColorByte(int color1){
    byte[] color = new byte[4];
    for (int i = 0; i < 4; i++) {
        color [i] = (byte)(color1 >>> (i * 8));
    }
    return color;
}

转为 Int :

public int getColorInt(byte [] color){
    int res = ((color[0] & 0xff) << 24) | ((color[1] & 0xff) << 16) |
          ((color[2] & 0xff) << 8)  | (color[3] & 0xff);
    return res;
}