简体   繁体   English

Java字节数组到有符号的Int

[英]Java byte Array to signed Int

I'm trying to convert a signed int variable to a 3 byte array and backwards. 我正在尝试将带符号的int变量转换为3字节数组并向后转换。

In the the function getColorint , I'm converting the int value to the byte array. 在函数getColorint中 ,我将int值转换为字节数组。 That works fine! 很好!

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

But if I try to convert the byte array back to the Integer with the getColorint function: 但是,如果我尝试使用getColorint函数将字节数组转换回Integer:

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

it only works for positive integer values. 它仅适用于正整数值。

Here is a screenshot during the debug: 这是调试期间的屏幕截图: 屏幕截图

My input int value is -16673281 but my output int value is 38143 . 我的输入int值为-16673281,但我的输出int值为38143

Can anyone help me? 谁能帮我?

Thanks :) 谢谢 :)

The Color class defines methods for creating and converting color ints. Color类定义用于创建和转换颜色int的方法。 Colors are represented as packed ints, made up of 4 bytes: alpha, red, green, blue. 颜色以打包的整数表示,由4个字节组成:alpha,红色,绿色,蓝色。 You should use it. 您应该使用它。

The problem here is that byte is signed. 这里的问题是字节已签名。 When you do int answer = color[2] with color[2] == -1 , then answer will be also -1, ie 0xffffffff, whereas you want it to be 255 (0xff). 当您用color[2] == -1进行int answer = color[2]时,答案也将为-1,即0xffffffff,而您希望它为255(0xff)。 You can use Guava 's UnsignedBytes as a remedy, or simply take color[i] & 0xff which casts it to int. 您可以使用Guava的UnsignedBytes作为补救措施,也可以只是采用color[i] & 0xff其强制转换为int。

As is Color represents in 4 bytes, you should store also an alpha channel. 正如Color以4个字节表示的那样,您还应该存储一个alpha通道。

From Int : 来自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;
}

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

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

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