Search code examples
c#bit-manipulationbit

How to insert a byte into an int starting at X position


I have an Int32 that is broken in to different sections, each with its own value.

Lets say I have:

byte version = 0x02
uInt32 packedValues = 0; 

How can I put the 0x02 in packedValues, starting at index 20, or any index.

Thanks!


Solution

  • Not sure what do you mean by index but it seems that you need to do some bit twiddling. Something along these lines:

    byte version = 0x02;
    var index = 20;
    uint packedValues = 0;
    
    var b1 = version << index;
    packedValues = (uint)((packedValues & ~(0xFF << index)) | (uint)(version << index));
    

    (packedValues & ~(0xFF << index)) - zeroes needed bits and the rest sets the bits from the source.