C# 获取 32 位 uint 的最后 10 位
C# Getting the last 10 bits of a 32 bit uint
我想要获取 32 位整数的最后 10 位,
基本上我所做的就是取一个数字并将其塞入前 22 位,我可以使用
很好地提取出该数字
int test = Convert.ToInt32(uIActivityId >> nMethodBits); //method bits == 10 so this just pushes the last ten bits off the range
其中测试结果是我在第一位输入的数字。
但现在我被难住了。所以我要问你们的问题是。如何获取 32 位整数的最后十位?
首先创建一个掩码,其中 1 位用于您想要的位,0 位用于您不感兴趣的位。然后使用二进制 &
仅保留相关位。
const uint mask = (1 << 10) - 1; // 0x3FF
uint last10 = input & mask;
public bool[] GetLast10Bits(int input) {
BitArray array = new BitArray(new []{input});
List<bool> bits = new List<bool>();
if (array.Length > 10) {
return Enumerable.Range(0, 10).Select(i => array[i]).ToArray();
}
return new bool[0];
}
int i = Convert.ToInt32("11100111101", 2);
int mask = Convert.ToInt32("1111111111", 2);
int test = Convert.ToInt32(( i&mask));
int j = Convert.ToInt32("1100111101", 2);
if (test == j)
System.Console.Out.WriteLine("it works");
这是另一种尝试!!
List<bool> BitsOfInt(int input , int bitCount)
{
List<bool> outArray = new BitArray (BitConverter.GetBytes(input)).OfType<bool>().ToList();
return outArray.GetRange(outArray.Count - bitCount, bitCount);
}
我想要获取 32 位整数的最后 10 位,
基本上我所做的就是取一个数字并将其塞入前 22 位,我可以使用
很好地提取出该数字int test = Convert.ToInt32(uIActivityId >> nMethodBits); //method bits == 10 so this just pushes the last ten bits off the range
其中测试结果是我在第一位输入的数字。
但现在我被难住了。所以我要问你们的问题是。如何获取 32 位整数的最后十位?
首先创建一个掩码,其中 1 位用于您想要的位,0 位用于您不感兴趣的位。然后使用二进制 &
仅保留相关位。
const uint mask = (1 << 10) - 1; // 0x3FF
uint last10 = input & mask;
public bool[] GetLast10Bits(int input) {
BitArray array = new BitArray(new []{input});
List<bool> bits = new List<bool>();
if (array.Length > 10) {
return Enumerable.Range(0, 10).Select(i => array[i]).ToArray();
}
return new bool[0];
}
int i = Convert.ToInt32("11100111101", 2);
int mask = Convert.ToInt32("1111111111", 2);
int test = Convert.ToInt32(( i&mask));
int j = Convert.ToInt32("1100111101", 2);
if (test == j)
System.Console.Out.WriteLine("it works");
这是另一种尝试!!
List<bool> BitsOfInt(int input , int bitCount)
{
List<bool> outArray = new BitArray (BitConverter.GetBytes(input)).OfType<bool>().ToList();
return outArray.GetRange(outArray.Count - bitCount, bitCount);
}