Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to binary zeros and ones [duplicate]

Tags:

string

c#

binary

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

like image 699
Kyara Programmer Avatar asked May 20 '13 23:05

Kyara Programmer


People also ask

How do you convert a string to a binary number?

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 string in C++?

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.

How do you convert data to binary in Python?

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.

Which typecast method is required to store string in a binary file?

WriteFile function (MSDN)


3 Answers

Here is an example:

foreach (char c in "Test")
    Console.WriteLine(Convert.ToString(c, 2).PadLeft(8, '0'));
like image 54
mitja.gti Avatar answered Oct 20 '22 13:10

mitja.gti


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.

like image 3
LemonCool Avatar answered Oct 20 '22 13:10

LemonCool


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

like image 1
cat_minhv0 Avatar answered Oct 20 '22 13:10

cat_minhv0