1

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

4 Answers 4

2
var val = 513; for(var pos=0;;pos++) { var x = 1 << pos; if(x > val) break; if((val & x) == x) { Console.WriteLine(pos); } } 
Sign up to request clarification or add additional context in comments.

3 Comments

Get off. What a load of nonsense. It's a matter of coding style and completely insignificant. Perhaps I should have used hungarian notation too?
Gave it a +1. It was helpful, just took me a little longer to read ancillary articles to see what type var would be int/uint by default. New to C#, may have been a trivial question. :)
Ah. Sorry for my explosive response. Been using var for so long now, I'm completely acclimatised!
1

The BitVector32 class is an utility class that can help you out for this, if you really want to keep a bit map.

Comments

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

Comments

0

To test bit #i in number n:

if ((n & (1 << i)) != 0) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.