位移和位掩码-示例代码 [英] Bit shifting and bit mask - sample code
问题描述
我遇到了一些代码,这些代码具有位掩码 0xff
和 0xff00
或16位二进制形式 00000000 11111111
和 11111111 00000000
.
I've come across some code which has the bit masks 0xff
and 0xff00
or in 16 bit binary form 00000000 11111111
and 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;
}
}
我正在尝试弄清在这种情况下(针对字节数组)使用这些位掩码的目的.我看不出会有什么不同?
I'm trying to work out what the purpose of using these bit masks in this context (against a byte array). I can't see what difference it would make?
在GZip压缩字符串的上下文中,因为此方法似乎是为GZip魔术数字编写的,十六进制为 35615
, 8B1F
和 10001011 00011111
二进制文件.
In the context of a GZip compressed string as this method seems to be written for the GZip magic number is 35615
, 8B1F
in Hex and 10001011 00011111
in binary.
我认为这可以交换字节吗?例如,假设我的输入字符串为 \ u001f \ u008b
Am I correct in thinking this swaps the bytes? So for example say my input string were \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)
.我想念什么?
To me it doesn't seem like the &
is doing anything to the original byte in both cases bytes[0] & 0xff
and (bytes[1] << 8) & 0xff00)
. What am I missing?
推荐答案
int gzipHeader = ((int) bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00);
byte
类型是Java,是 signed .如果将 byte
强制转换为 int
,则其符号将被扩展.&0xff
用于屏蔽从符号扩展中获得的 1
位,从而有效地将 byte
视为未签名.
The type byte
is Java is signed. If you cast a byte
to an int
, its sign will be extended. The & 0xff
is to mask out the 1
bits that you get from sign extension, effectively treating the byte
as if it is unsigned.
与 0xff00
一样,不同之处在于,首先将字节向左移了8位.
Likewise for 0xff00
, except that the byte is first shifted 8 bits to the left.
所以,它的作用是:
- 获取第一个字节
bytes [0]
,将其强制转换为int
,并屏蔽符号扩展位(将其视为无符号字节) - 获取第二个字节,将其转换为
int
,向左移8位,并屏蔽掉符号扩展位 - 用
|
组合值
- take the first byte,
bytes[0]
, cast it toint
and mask out the sign-extended bits (treating the byte as if it is unsigned) - take the second byte, cast it to
int
, shift it left by 8 bits, and mask out the sign-extended bits - combine the values with
|
请注意,左移有效地交换了字节.
Note that the shift left effectively swaps the bytes.
这篇关于位移和位掩码-示例代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!