I want to convert a string into a byte array. (Yes) I have seen multiple questions already asked on this topic, but I did not find the answers to be too helpful. In most cases the questions were rather lacking. I've been doing some research, and I will post my findings below.
These are all ways I found to convert a string into a byte array in C#.net. Many of these were coded on my own.
1)
private byte[] getByte(string s)
{
Byte[] b = new byte[s.Length];
for (int i = 0; i < s.Length; i++)
{
char c = Convert.ToChar(s.Substring(i, 1));
b[i] = Convert.ToByte(c);
}
return b;
}
2)
System.Text.ASCIIEncoding encoding=new System.Text.ASCIIEncoding();
Byte[] bytes = encoding.GetBytes(yourString)
3) ** Of course there is the file.ReadAllBytes method, but I am not reading this data from a file.
So, does anyone here know of a C# equivalent to the following (which is VB6)?
Dim sData as string
Dim b() as byte
sData = "Test String in VB6"
b() = strconv(sData, VbFromUnicode)
Thank you very much. I look forward to seeing some great answers!
System.Text.UTF8Encoding encoding=new System.Text.UTF8Encoding();
return encoding.GetBytes(str);
Your option 2 is almost there, you just need to change the encoder
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
byte[] unicodeStringAsBytes = UTF8.GetBytes(myString);
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