Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String to Binary in C#

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; } 
like image 213
Nano HE Avatar asked Apr 14 '11 13:04

Nano HE


People also ask

How do you convert a string to binary?

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) .

What is binary number in C?

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.


2 Answers

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)); 
like image 165
Jaapjan Avatar answered Sep 23 '22 12:09

Jaapjan


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; } 
like image 26
Matthew Layton Avatar answered Sep 21 '22 12:09

Matthew Layton