S
SpookyET
For some reason the method reverses the array, which is very annoying. If
I put in 00001000 which is 8, i get back 00010000 which is 16. If I put in
00000100 (4), I get back 00100000 (32). This means that CopyTo is
useless, since I have to reverse it to get it right.
public static void Main()
{
bool[] bools = new bool[8] { false, false, false, false, false, true,
false, false};
BitArray bits = new BitArray(bools);
byte myByte = 0;
byte[] myByteArray = new byte[bits.Count / 8];
int index;
for (index = 0; index < bits.Length; index++)
{
myByte <<= 1;
myByte |= Convert.ToByte(bits[index]);
}
// An uglier way.
// for (index = 0; index < bits.Length; index++)
// {
// myByte = ((byte)((myByte << 1) | (bits[index] ? 1 : 0)));
// }
bits.CopyTo(myByteArray, 0);
Console.WriteLine(myByte);
Console.WriteLine(myByteArray[0]);
Console.ReadLine();
}
Wouldn't it be better if there was a struct System.Bit with a C# alias of
"bit", that accepts 0/1 and true/false.
bit myBit = 1;
byte myByte = 0;
myByte <<= 1;
byte |= myBit;
This is much easier and cleaner, and no casting. I know about enum with
the [FlagsAttribute], but this has nothing to do with flags/options, for
those of you that might suggest that.
I put in 00001000 which is 8, i get back 00010000 which is 16. If I put in
00000100 (4), I get back 00100000 (32). This means that CopyTo is
useless, since I have to reverse it to get it right.
public static void Main()
{
bool[] bools = new bool[8] { false, false, false, false, false, true,
false, false};
BitArray bits = new BitArray(bools);
byte myByte = 0;
byte[] myByteArray = new byte[bits.Count / 8];
int index;
for (index = 0; index < bits.Length; index++)
{
myByte <<= 1;
myByte |= Convert.ToByte(bits[index]);
}
// An uglier way.
// for (index = 0; index < bits.Length; index++)
// {
// myByte = ((byte)((myByte << 1) | (bits[index] ? 1 : 0)));
// }
bits.CopyTo(myByteArray, 0);
Console.WriteLine(myByte);
Console.WriteLine(myByteArray[0]);
Console.ReadLine();
}
Wouldn't it be better if there was a struct System.Bit with a C# alias of
"bit", that accepts 0/1 and true/false.
bit myBit = 1;
byte myByte = 0;
myByte <<= 1;
byte |= myBit;
This is much easier and cleaner, and no casting. I know about enum with
the [FlagsAttribute], but this has nothing to do with flags/options, for
those of you that might suggest that.