我得到一个像513这样的数字。我需要将这个数字转换为bitmask32,然后我需要计算每个1位在数组中的位置
例如513 =0和9
如何将数字转换为bit32,然后再读取值?
现在,我只是将数字转换为字符串二进制值:
string bit = Convert.ToString(513, 2);有没有更有效的方法来做到这一点?如何将值转换为位数组?
谢谢
发布于 2011-04-25 21:40:10
var val = 513;
for(var pos=0;;pos++)
{
var x = 1 << pos;
if(x > val) break;
if((val & x) == x)
{
Console.WriteLine(pos);
}
}发布于 2011-04-25 21:46:09
如果您真的想保留位图,BitVector32类是一个实用程序类,它可以帮助您解决这一问题。
发布于 2011-04-25 22:20:49
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);
}https://stackoverflow.com/questions/5778823
复制相似问题