I'm wondering if there are built in classes for working with binary numbers and converting any number (in this case decimal) to a binary and vice-versa. For example if I want to check if the third bit is 1
I can use the &
bitwise operator but I feel it will be much more simple if there is indeed a way to convert the decimal to binary and check the value on the position I want. I've searched and find examples using BitArray
but for some reason it throws me an error the it does not exist and I'm wondering if it's outdated. Also I tried MS library and found BitConverter.GetBytes(value)
but I'm not sure what it does at all because when I try the example which is :
int value = 12345678;
byte[] bytes = BitConverter.GetBytes(value);
Console.WriteLine(BitConverter.ToString(bytes));
The output is 4E-61-BC-00
which I'm not sure what actually is. What I'm looking for is if I have like int i = 247; // 11110111
and then:
i[0] = 1;
i[1] = 1;
i[2] = 1;
i[3] = 0;
i[4] = 1;
i[5] = 1;
i[6] = 1;
i[7] = 1;
So I can get 1 or 0 for any position.
i[2] = 1;
-
Integers are already in binary, it's when you want the decimal representation that they are converted.user555045– user5550452012年09月12日 16:50:38 +00:00Commented Sep 12, 2012 at 16:50
2 Answers 2
You should use BitArray just make sure your added using System.Collections; to your CS file. You can pass a new BitArray a byte[], which will handle the conversion for you.
Comments
Well, yes, you can create a BitArray
from an int
:
int i = 247;
BitArray b = new BitArray(i);
And then you can check the third bit:
if (b[2])
{
// the bit is set
}
The elements in the BitArray
are Boolean
, so to set the third bit, you'd write:
b[2] = true;
Converting back to an int
is a bit of a pain, though. because you have to use CopyTo
to copy the BitArray
to an int[]
, and then access the first item in the int[]
.
I don't understand why you'd want to go through the headache. It's going to be a lot slower and more cumbersome than using the bitwise &
operator. You could easily create constants for the different bit values:
const int bit0 = 0x01;
const int bit1 = 0x02;
const int bit2 = 0x04;
const int bit3 = 0x08;
const int bit4 = 0x10;
// etc.
And then:
if ((i & bit2) != 0)
{
// the bit is set
}
Setting a single bit is:
i |= bit2;
Resetting a bit is:
i &= ~bit2;
5 Comments
BitArray
.BitArray
and stick to the way Jim Mischel has shown..