I want to convert string to binary and I tried this code
byte[] arr = System.Text.Encoding.ASCII.GetBytes(aa[i]);
and this
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
byte[] arr= encoding.GetBytes(aa[i]);
but it returned numbers not binary say If I write 'm' it convert it to "0109" and I want to convert to zeros & Ones only Thanks in advance
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) .
A binary string is a sequence of bytes. Unlike a character string which usually contains text data, a binary string is used to hold non-traditional data such as pictures. The length of a binary string is the number of bytes in the sequence. A binary string has a CCSID of 65535.
In Python, you can simply use the bin() function to convert from a decimal value to its corresponding binary value. And similarly, the int() function to convert a binary to its decimal value. The int() function takes as second argument the base of the number to be converted, which is 2 in case of binary numbers.
WriteFile function (MSDN)
Here is an example:
foreach (char c in "Test")
Console.WriteLine(Convert.ToString(c, 2).PadLeft(8, '0'));
I'm not sure I completely understand your question, but if you want to convert text to binary this is how it is done:
public byte[] ToBinary(string stringPassed)
{
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
return encoding.GetBytes(stringPassed);
}
You need to pass the whole string, not the characters in the string.
You could use : Convert.ToByte(string value, int fromBase)
According to MSDN :
fromBase Type: System.Int32 The base of the number in value, which must be 2, 8, 10, or 16.
For more detail, see this link : Convert.ToByte()
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