I am getting a number such as 513. I need to convert this number to a bitmask32 then I need to count where each 1 bit is in the array
For Example 513 = 0 and 9
How would I go about converting the number to a bit32 then reading the values?
Right now I am just converting the number to a string binary value:
string bit = Convert.ToString(513, 2);
Would there be a more effective way to do this? How would I convert the value to a bit array?
Thanks
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);
}
要测试数字n
位#i:
if ((n & (1 << i)) != 0)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.