String to Binary in C#
Here you go:
public static byte[] ConvertToByteArray(string str, Encoding encoding)
{
return encoding.GetBytes(str);
}
public static String ToBinary(Byte[] data)
{
return string.Join(" ", data.Select(byt => Convert.ToString(byt, 2).PadLeft(8, '0')));
}
// Use any sort of encoding you like.
var binaryString = ToBinary(ConvertToByteArray("Welcome, World!", Encoding.ASCII));
It sounds like you basically want to take an ASCII string, or more preferably, a byte[] (as you can encode your string to a byte[] using your preferred encoding mode) into a string of ones and zeros? i.e. 101010010010100100100101001010010100101001010010101000010111101101010
This will do that for you...
//Formats a byte[] into a binary string (010010010010100101010)
public string Format(byte[] data)
{
//storage for the resulting string
string result = string.Empty;
//iterate through the byte[]
foreach(byte value in data)
{
//storage for the individual byte
string binarybyte = Convert.ToString(value, 2);
//if the binarybyte is not 8 characters long, its not a proper result
while(binarybyte.Length < 8)
{
//prepend the value with a 0
binarybyte = "0" + binarybyte;
}
//append the binarybyte to the result
result += binarybyte;
}
//return the result
return result;
}
The following will give you the hex encoding for the low byte of each character, which looks like what you're asking for:
StringBuilder sb = new StringBuilder();
foreach (char c in asciiString)
{
uint i = (uint)c;
sb.AppendFormat("{0:X2}", (i & 0xff));
}
return sb.ToString();