[英]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.