jjd*_*v80 1 c# bit-manipulation
有人可以解释以下代码的作用.
private int ReadInt32(byte[] _il, ref int position)
{
return (((il[position++] | (il[position++] << 8)) | (il[position++] << 0x10)) | (il[position++] << 0x18));
}
Run Code Online (Sandbox Code Playgroud)
我不确定我理解这种方法中的按位运算符是如何工作的,有些人可以帮我分解一下吗?
整数以字节数组的形式给出.然后将每个字节向左移位0/8/16/24个位置,并将这些值相加以得到整数值.
这是Int32十六进制格式:
0x10203040
Run Code Online (Sandbox Code Playgroud)
它表示为以下字节数组(小端结构,因此字节顺序相反):
[0x40, 0x30, 0x20, 0x10]
Run Code Online (Sandbox Code Playgroud)
为了从数组中构建整数,每个元素都被移位,即执行以下逻辑:
a = 0x40 = 0x00000040
b = 0x30 << 8 = 0x00003000
c = 0x20 << 16 = 0x00200000
d = 0x10 << 24 = 0x10000000
Run Code Online (Sandbox Code Playgroud)
那么这些值是OR在一起:
int result = a | b | c | d;
this gives:
0x00000040 |
0x00003000 |
0x00200000 |
0x10000000 |
------------------
0x10203040
Run Code Online (Sandbox Code Playgroud)