【发布时间】:2015-05-19 14:03:38
【问题描述】:
我遇到了一些具有位掩码 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) 两种情况下都没有对原始字节做任何事情。我错过了什么?
【问题讨论】:
标签: java bit-manipulation