[英]A Built-in Function to Convert from String to Byte
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.
真的 - 你的rappraoch坏了。 You ASSUME that the lower byte is the byte you need.
您假设低位字节是您需要的字节。 Waht you try to achieve?
你试图实现吗? ASCII representation of the string?
字符串的ASCII表示? What codepage?
什么代码页?
Check the following page: 请查看以下页面:
http://msdn.microsoft.com/en-us/library/system.text.encoding.aspx http://msdn.microsoft.com/en-us/library/system.text.encoding.aspx
Use one of the classes mentioned there, possibly the ASCIIEncoding class. 使用其中提到的类之一,可能是ASCIIEncoding类。
The .NET Framework provides the following implementations of the Encoding class to support current Unicode encodings and other encodings: .NET Framework提供了Encoding类的以下实现,以支持当前的Unicode编码和其他编码:
The .NET Framework provides the following implementations of the Encoding class to support current Unicode encodings and other encodings: .NET Framework提供了Encoding类的以下实现,以支持当前的Unicode编码和其他编码:
There is. 有。 It is
Encoding.GetBytes
. 它是
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. 将ASCIIEncoding替换为您要使用的编码。
string s = "Like this";
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
byte[] b = enc.GetBytes(s);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.