1

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?

5
  • msdn.microsoft.com/en-us/library/6a71f45d%28v=vs.110%29.aspx ? Commented Apr 10, 2013 at 10:08
  • 1
    I'd change it to return (((il[position] | (il[position+1] << 8)) | (il[position+2] << 0x10)) (not answering the question, someone has already done that, it's just that the position++ stuff is just hard to read and unnecessary) Commented Apr 10, 2013 at 10:10
  • 1
    @MatthewWatson, I agree that it makes far more sense, but it seems that it is used in a loop over a buffer from an external function, as the position argument is ref int so the callee likely depends on index being updated. still, I would do it like you and just add pos += 4 at the end Commented Apr 10, 2013 at 10:18
  • @ZdeslavVojkovic Ah yes, quite right. Probably position += sizeof(int) would be even more expressive. Commented Apr 10, 2013 at 10:31
  • @MatthewWatson, right, I completely forgot that C# also has sizeof operator. Commented Apr 10, 2013 at 11:49

2 Answers 2

8

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 i.e. 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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, it makes much more sense now! :)
3

Think of it like this:

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.