Saturday, October 30, 2010

Extracting individual bits from a byte array in C Sharp

Byte Array to bit conversion operation is often required operation when you are operating at bit level. The following program shows how to convert a string to its ASCII equivalent and read it bit by bit.


...
string txt = "C Sharp is cool"; //let txt be any text
byte[] txt_byt = Encoding.ASCII.GetBytes(txt); //txt_byt contains an array of byte equivalent(ASCII) of each character of the string
BitArray b_ar = new BitArray(txt_byt); //Now b_ar is a Bit Array that contains all the bits extracted from the byte array txt_byt. And note that bits are stored as boolean values, so the comparison will be
for (int i = 0; i < b_ar.Length; i++)
{
if (b_ar[i] == false)
{
Console.Write("0");
}
else
{
Console.Write("1");
}
}
...

No comments:

Post a Comment