Convert bitarray to string
Could someone help me to convert bittarray to string properly? I wrote this:
static String BitArrayToStr(BitArray ba)
{
byte[] strArr = new byte[ba.Length / 8];
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
for (int i = 0; i < ba.Length / 8; i++)
{
for (int index = i * 8, m = 1; index < i * 8 + 8; index++, m *= 2)
{
strArr[i] += ba.Get(index) ? (byte)m : (byte)0;
}
}
return encoding.GetStri开发者_如何学Gong(strArr);
}
but on the output I have this: "���*Ȱ&����L9��q�zȲP���*Ȱ&����L9��q�zȲP���*Ȱ&Y(W�" -many unrecognised symbols, what shoud I do?
You can use this extension method:
public static string ToBitString(this BitArray bits)
{
var sb = new StringBuilder();
for (int i = 0; i < bits.Count; i++)
{
char c = bits[i] ? '1' : '0';
sb.Append(c);
}
return sb.ToString();
}
Are you sure your input bit array is from a string that was encoded as ASCII?
Using your code I did the following test
string s = "Hello World";
byte[] bytes = Encoding.ASCII.GetBytes(s);
BitArray b = new BitArray(bytes);
string s2 = BitArrayToStr(b);
And s2 came out with the value Hello World
as expected.
Update:
As described in the comments, the ASCII Encoder only handles the bytes 32-127 as printable characters, 0-32 which are control characters will display symbols and everything above 127 will use the ASCII fallback to handle the bad bytes.
Here is a quote from MSDN
http://msdn.microsoft.com/en-us/library/system.text.decoderfallback.aspx
A decoding operation can fail if the input byte sequence cannot be mapped by the encoding. For example, an ASCIIEncoding object cannot decode a byte sequence that yields a character having a code point value that is outside the range U+0000 to U+007F.
When an encoding or decoding conversion cannot be performed, the .NET Framework provides a failure-handling mechanism called a fallback. Your application can use predefined .NET Framework encoder and decoder fallbacks, or it can create a custom encoder fallback derived from the EncoderFallback and EncoderFallbackBuffer classes or a custom decoder fallback derived from the DecoderFallback and DecoderFallbackBuffer classes.
You could use this method to convert the BiArray into a byte array:
public static byte[] ToByteArray(this BitArray bits)
{
int numBytes = bits.Count / 8;
if (bits.Count % 8 != 0) numBytes++;
byte[] bytes = new byte[numBytes];
int byteIndex = 0, bitIndex = 0;
for (int i = 0; i < bits.Count; i++)
{
if (bits[i])
bytes[byteIndex] |= (byte)(1 << (7 - bitIndex));
bitIndex++;
if (bitIndex == 8) {
bitIndex = 0;
byteIndex++;
}
}
return bytes;
}
And then:
BitArray ba = Fill();
string result = Encoding.ASCII.GetString(ba.ToByteArray());
http://social.msdn.microsoft.com/Forums/en-US/Vsexpressvcs/thread/e2403fd6-61ce-4487-b11a-fddcef40c87f
精彩评论