Share via


Convert int to bool[]

Question

Sunday, October 3, 2010 10:07 PM

Hi

I want to convert int value to bool array, just like "calc.exe" do. Any ideas? Maybe loop of division by 2 or something?

All replies (4)

Monday, October 4, 2010 12:08 AM ✅Answered

int source = 123;

bool[] target = new bool[32];

for (int i = 0; i < 32; i++)
{
    target[i] = ((source >> i) & 1) == 1;
}

or

var source = 123;
var bitArray = new BitArray(new[] {source});
            
var target = new bool[32];
bitArray.CopyTo(target, 0);

Monday, October 4, 2010 12:10 AM ✅Answered

Hi XspeedPL,

 

you can use AND(&) operator to determine which bit is flaged.

 

for example we need bit 5, so we use following line:

bool flaged = (number >> 5 & 0x01) == 0x01;

 

so it's easy. I Provide a sample for you.

 

With this code sample you can:

* Change a Bit from Integer

* Convert Integer to Boolean array

* Convert Boolean Array to Integer

* Convert integer Bits to string

 Download MySample From SkyDrive

Any fool can know. The point is to understand.(Albert Einstein)


Sunday, October 3, 2010 10:47 PM

What do you mean with "just like 'calc.exe' do"? I've never seen calc.exe producing arrays. Are you refereing to a conversion from decimal to binary?

You can use the BitArray class to take each bit of an int as a boolean value.


Sunday, October 3, 2010 10:58 PM

Perhaps the OP meant show as Hex?

 

Depending on the context, maybe this helps:

 

   int x = 31;
   Console.WriteLine("{0:x}", x);

Produces 1F

Mike