I have a function to convert string to hex as this,
public static string ConvertToHex(string asciiString) { string hex = ""; foreach (char c in asciiString) { int tmp = c; hex += String.Format("{0:x2}", (uint)System.Convert.ToUInt32(tmp.ToString())); } return hex; }
Could you please help me write another string to Binary function based on my sample function?
public static string ConvertToBin(string asciiString) { string bin = ""; foreach (char c in asciiString) { int tmp = c; bin += String.Format("{0:x2}", (uint)System.Convert.????(tmp.ToString())); } return bin; }
To convert a string to binary, we first append the string's individual ASCII values to a list ( l ) using the ord(_string) function. This function gives the ASCII value of the string (i.e., ord(H) = 72 , ord(e) = 101). Then, from the list of ASCII values we can convert them to binary using bin(_integer) .
ADVERTISEMENT. ADVERTISEMENT. Binary number is a base 2 number because it is either 0 or 1. Any combination of 0 and 1 is binary number such as 1001, 101, 11111, 101010 etc.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With