Extract n bits and create int from Int32

Viewed 98

I have a 32 bit int that has two value packed into it by a connected device.

The first 10 bits is X and the last 22 bits is Y.

How do I go about extracting these 2 numbers from the original int?

1 Answers

You can use bit-right-shifts operator (>>) and and-bit-masks with the AND operator (&):

using System;
                    
public class Program
{
    public static void Main()
    {
        int source = unchecked ((int)0xF45ABCDE);

        //10 LSB bits
        int X = source & 0x000003FF; //mask 10 LSBs

        //22 MSB bits: bitshift + mask
        int Y = (source >> 10) & 0x003FFFFF; 
                    
        Console.WriteLine("                  :MSB                          LSB");   
        Console.WriteLine("Source            :" + Convert.ToString(source, 2).PadLeft(32,'0'));
        Console.WriteLine("source shift >> 10:" + Convert.ToString((source >> 10), 2).PadLeft(32,'0'));
        Console.WriteLine("Mask X            :" + Convert.ToString(0x000003FF, 2).PadLeft(32,'0'));
        Console.WriteLine("Mask Y            :" + Convert.ToString(0x003FFFFF, 2).PadLeft(32,'0'));
        Console.WriteLine("X                 :" + Convert.ToString(X, 2).PadLeft(32,'0'));  
        Console.WriteLine("Y                 :" + Convert.ToString(Y, 2).PadLeft(32,'0'));
    }
}

output:

                  :MSB                          LSB
Source            :11110100010110101011110011011110
source shift >> 10:11111111111111010001011010101111
Mask X            :00000000000000000000001111111111
Mask Y            :00000000001111111111111111111111
X                 :00000000000000000000000011011110
Y                 :00000000001111010001011010101111

Note, you'll need the mask if you are using ints, see: msdn

If the left-hand operand is of type int or long, the right-shift operator performs an arithmetic shift: the value of the most significant bit (the sign bit) of the left-hand operand is propagated to the high-order empty bit positions. That is, the high-order empty bit positions are set to zero if the left-hand operand is non-negative and set to one if it's negative.

Related