C#将BitMask32的数字转换为值

| 我得到一个数字,例如513。我需要将此数字转换为bitmask32,然后我需要计算数组中每个1位的位置 例如 513 = 0和9 我将如何将数字转换为bit32然后读取值? 现在,我只是将数字转换为字符串二进制值:
string bit = Convert.ToString(513, 2);
会有更有效的方法吗?如何将值转换为位数组? 谢谢     
已邀请:
var val = 513;
for(var pos=0;;pos++)
{
    var x = 1 << pos;
    if(x > val) break;
    if((val & x) == x)
    {
        Console.WriteLine(pos);
    }
}
    
如果确实要保留位图,则BitVector32类是一个实用程序类,可以为您提供帮助。     
using System.Collections;

int originalInt = 7;
byte[] bytes = BitConverter.GetBytes(originalInt);
BitArray bits = new BitArray(bytes);
int ndx = 9; //or whatever ndx you actually care about

if (bits[ndx] == true)
{
     Console.WriteLine(\"Bit at index {0} is on!\", ndx);
}
    
要测试编号“ 3”中的位#i:
if ((n & (1 << i)) != 0)
    

要回复问题请先登录注册