The main problem is that your input function is wrong.
If you pass the string "Hello" the returned string is
"10010001100101110110011011001101111" (35 characters ??? )
but this is not a correct representation in binary of the word Hello
where every character should be represented by a series of 8 0|1 (total 40 characters)
The main reason for this error lies in the Convert.ToString
that strips away the leading zeros from the byte passed to the conversion.
So the letter H
should be 01001000
(8 chars) but the conversion returns 1001000
(7 chars) thus everything that follow is wrong and impossible to correctly convert back.
You could fix the input function with
string GetBits(string input)
{
StringBuilder sb = new StringBuilder();
foreach (byte b in Encoding.UTF8.GetBytes(input))
{
string temp = Convert.ToString(b, 2);
// This ensure that 8 chars represent the 8bits
temp = "00000000".Substring(temp.Length) + temp;
sb.Append(temp);
}
return sb.ToString();
}
While the conversion back to "Hello" could be written as
string GetString(string input)
{
// Probably a checking on the input length as multiple of 8
// should be added here....
StringBuilder sb = new StringBuilder();
while (input.Length > 0)
{
string block = input.Substring(0, 8);
input = input.Substring(8);
int value = 0;
foreach (int x in block)
{
int temp = x - 48;
value = (value << 1) | temp;
}
sb.Append(Convert.ToChar(value));
}
return sb.ToString();
}