Search code examples
c#.netbitwise-operatorsfixedbit-shift

Odd bit shifting results in C#


Given that i have a uint value of 2402914, and i would like to grab the leftmost 17 bits, where is the fault in my logic by doing this code:

int testop = 0;
byte[] myArray = BitConverter.GetBytes(2402914);    
fixed (byte* p = &myArray[0])    
{   
    testop = *p >> 15;    
}

my expected output is

50516.

Solution

  • *p just gives you the first byte; it is equivalent to p[0]. You'll have to use shifting and ORing to combine bits from the first three bytes (or the last three bytes, depending on endianness...)

    If this code is not a simplified version of something more complicated and you're actually trying to just extract the leftmost 17 bits from an int, this should do:

    int testop = (someInt >> 15) & 0x1ffff;
    

    (Edit: Added & 0x1ffff to make it work for negative integers too; thanks to @James.)