Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
358 views
in Technique[技术] by (71.8m points)

c# - Extract n bits and create int from Int32

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?

question from:https://stackoverflow.com/questions/65617797/extract-n-bits-and-create-int-from-int32

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...