繁体   English   中英

Java字节数组到有符号的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函数将字节数组转换回Integer:

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

它仅适用于正整数值。

这是调试期间的屏幕截图: 屏幕截图

我的输入int值为-16673281,但我的输出int值为38143

谁能帮我?

谢谢 :)

Color类定义用于创建和转换颜色int的方法。 颜色以打包的整数表示,由4个字节组成:alpha,红色,绿色,蓝色。 您应该使用它。

这里的问题是字节已签名。 当您用color[2] == -1进行int answer = color[2]时,答案也将为-1,即0xffffffff,而您希望它为255(0xff)。 您可以使用Guava的UnsignedBytes作为补救措施,也可以只是采用color[i] & 0xff其强制转换为int。

正如Color以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;
}

要诠释:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM