I have the following function:
public static byte[] StringToByte(string str)
{
int length = str.Length;
byte[] ba = new byte[length];
for (int i = 0; i < length; i++)
{
ba[i] = (byte)str[i];
}
return ba;
}
I wonder whether there is a built-in function for this method?
System.Text.Encoding.GetBytes(string)
System.Text.ASCIIEncoding encoding=new System.Text.ASCIIEncoding();
byte[] bytes= encoding.GetBytes(stringData);
Does not work. Really - you rappraoch is broken. You ASSUME that the lower byte is the byte you need. Waht you try to achieve? ASCII representation of the string? What codepage?
Check the following page:
http://msdn.microsoft.com/en-us/library/system.text.encoding.aspx
Use one of the classes mentioned there, possibly the ASCIIEncoding class.
The .NET Framework provides the following implementations of the Encoding class to support current Unicode encodings and other encodings:
The .NET Framework provides the following implementations of the Encoding class to support current Unicode encodings and other encodings:
There is. It is Encoding.GetBytes
.
To be exact, and with an example:
public static byte[] StrToByteArray(string str) {
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
return encoding.GetBytes(str);
}
Replace ASCIIEncoding with the encoding you'd like to use.
string s = "Like this";
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
byte[] b = enc.GetBytes(s);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.