[英]Mimetype detection - What is the purpose of & 0xff in this code?
以下是用於使用幻數檢測文件的mime類型的代碼的摘錄。
我可以理解十六進制是這里的重點。
但是,為什么要使用int
,為什么要與0xFF按位與?
byte[] header = new byte[11];
System.arraycopy(data, 0, header, 0, Math.min(data.length, header.length));
int c1 = header[0] & 0xff;
int c2 = header[1] & 0xff;
int c3 = header[2] & 0xff;
int c4 = header[3] & 0xff;
int c5 = header[4] & 0xff;
int c6 = header[5] & 0xff;
int c7 = header[6] & 0xff;
int c8 = header[7] & 0xff;
int c9 = header[8] & 0xff;
int c10 = header[9] & 0xff;
int c11 = header[10] & 0xff;
if (c1 == 0xCA && c2 == 0xFE && c3 == 0xBA && c4 == 0xBE) // CAFEBABE
{
return "application/java-vm";
}
在Java中, byte
是帶符號的類型。 例如, 0xFF
作為byte
實際上是-1作為int
。 結果是(byte) 0xFF != 0xFF
,這可能會造成混淆。 因此,當嘗試將byte
值轉換為int
時將其視為無符號時,應始終寫入myByte & 0xFF
以確保在不希望出現符號時不將其擴展。
& 0xff
將高位設置為0,僅考慮最后8位
header[0] & 0xff;
屏蔽位以僅生成8位/ 2字節。
為什么??
在內存方面 ,它們只使用16位無符號二進制int的補碼中的8位,而不是浪費8位。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.