我遇到了一些代码,其中有位掩码0xff
和0xff00
,或以16位二进制形式表示为00000000 11111111
和11111111 00000000
。
/**
* Function to check if the given string is in GZIP Format.
*
* @param inString String to check.
* @return True if GZIP Compressed otherwise false.
*/
public static boolean isStringCompressed(String inString)
{
try
{
byte[] bytes = inString.getBytes("ISO-8859-1");
int gzipHeader = ((int) bytes[0] & 0xff)
| ((bytes[1] << 8) & 0xff00);
return GZIPInputStream.GZIP_MAGIC == gzipHeader;
} catch (Exception e)
{
return false;
}
}
我试图弄清楚在这种情况下(针对字节数组),使用这些位掩码的目的是什么。我看不出会有什么区别?
在GZip压缩字符串的上下文中,因为这个方法似乎是为GZip魔术数字编写的,所以该魔术数字是35615
,十六进制为8B1F
,二进制为10001011 00011111
。
我是否正确地认为这会交换字节顺序?例如,假设我的输入字符串为\u001f\u008b
。
bytes[0] & 0xff00
bytes[0] = 1f = 00011111
& ff = 11111111
--------
= 00011111
bytes[1] << 8
bytes[1] = 8b = 10001011
<< 8 = 10001011 00000000
((bytes[1] << 8) & 0xff00)
= 10001011 00000000 & 0xff00
= 10001011 00000000
11111111 00000000 &
-------------------
10001011 00000000
所以
00000000 00011111
10001011 00000000 |
-----------------
10001011 00011111 = 8B1F
对我来说,无论是在
bytes[0] & 0xff
还是(bytes[1] << 8) & 0xff00)
的情况下,&
似乎对原始字节没有任何影响。我错过了什么吗?