gpt4 book ai didi

c# - 提取 n 位并从 Int32 创建 int

转载 作者:行者123 更新时间:2023-12-04 01:08:18 25 4
gpt4 key购买 nike

我有一个 32 位 int,它有两个由连接的设备打包到其中的值。

前10位为X,后22位为Y。

如何从原始 int 中提取这 2 个数字?

最佳答案

您可以使用位右移运算符 (>>)与运算符的位掩码 (&) :

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'));
}
}

输出:

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

请注意,如果您使用 int,则需要掩码,请参阅: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.

关于c# - 提取 n 位并从 Int32 创建 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65617797/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com