My goal is to be able to convert a string into binary code that is still a string. I am able to turn the string into byte[] but not back to a string without decoding it.
3 Answers
You can use the Convert method for that:
byte [] bytesToEncode = Encoding.UTF8.GetBytes (inputText);
string encodedText = Convert.ToBase64String (bytesToEncode);
2 Comments
MichaelS
I guess that's exactly what he wants. 'to a string of binary'
Royi Namir
Yes I missed the part where he wanted "still as a string"
If you can encode/decode a byte, e.g.
private static String ToBinary(Byte value) {
StringBuilder Sb = new StringBuilder(8);
Sb.Length = 8;
for (int i = 0; i < 8; ++i) {
Sb[7 - i] = (Char) ('0' + value % 2);
value /= 2;
}
return Sb.ToString();
}
private static Byte FromBinary(String value) {
int result = 0;
for (int i = 0; i < value.Length; ++i)
result = result * 2 + value[i] - '0';
return (Byte) result;
}
You can easily encode/decode a whole string:
// Encoding...
String source = "abc";
// 011000010110001001100011
String result = String.Join("", UTF8Encoding.UTF8.GetBytes(source).Select(x => ToBinary(x)));
...
// Decoding...
List<Byte> codes = new List<Byte>();
for (int i = 0; i < result.Length; i += 8)
codes.Add(FromBinary(result.Substring(i, 8)));
// abc
String sourceBack = UTF8Encoding.UTF8.GetString(codes.ToArray());