C# Bitwise Operators

Could someone please explain what the following code does.

private int ReadInt32(byte[] _il, ref int position)
{
    return (((il[position++] | (il[position++] << 8)) | (il[position++] << 0x10)) | (il[position++] << 0x18));
}

I'm not sure I understand how the bitwise operators in this method work, could some please break it down for me?


The integer is given as a byte array. Then each byte is shifted left 0/8/16/24 places and these values are summed to get the integer value.

This is an Int32 in hexadecimal format:

0x10203040

It is represented as following byte array (little endian architecture, so bytes are in reverse order):

[0x40, 0x30, 0x20, 0x10]

In order to build the integer back from the array, each element is shifted ie following logic is performed:

a = 0x40        = 0x00000040
b = 0x30 << 8   = 0x00003000
c = 0x20 << 16  = 0x00200000
d = 0x10 << 24  = 0x10000000

then these values are OR'ed together:

int result = a | b | c | d;

this gives:

0x00000040 |
0x00003000 | 
0x00200000 |
0x10000000 |
------------------
0x10203040

像这样想:

var i1 = il[position];
var i2 = il[position + 1] << 8;  (<< 8 is equivalent to * 256)
var i3 = il[position + 2] << 16; 
var i4 = il[position + 3] << 24;

position = position + 4;

return i1 | i2 | i3 | i4;
链接地址: http://www.djcxy.com/p/36376.html

上一篇: 太多'if'陈述?

下一篇: C#按位运算符