[英]Convert from 2 or 4 bytes to signed/unsigned short/int
我必須將字節轉換為signed / unsigned int或short。
以下方法是正確的嗎? 哪個是簽名的,哪個是未簽名的?
字節順序:LITTLE_ENDIAN
public static int convertTwoBytesToInt1(byte b1, byte b2) {
return (int) ((b2 << 8) | (b1 & 0xFF));
}
VS.
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);
}
VS.
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));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.