问题描述
我有一个包含二进制数据(非文本数据)的字符串.
I have a string which contains binary data (non-text data).
如何将其转换为原始字节数组?
How do I convert this to a raw byte array?
推荐答案
根据定义,C#中的字符串不包含二进制数据.它由一系列Unicode字符组成.
A string in C# - by definition - does not contain binary data. It consists of a sequence of Unicode characters.
如果您的字符串在ASCII(7位)字符集中仅包含Unicode字符,则可以使用编码.ASCII将字符串转换为字节:
If your string contains only Unicode characters in the ASCII (7-bit) character set, you can use Encoding.ASCII to convert the string to bytes:
byte[] result = Encoding.ASCII.GetBytes(input);
如果您的字符串包含u0000-u00ff范围内的Unicode字符,并且想要将它们解释为字节,则可以将这些字符转换为字节:
If you have a string that contains Unicode characters in the range u0000-u00ff and want to interpret these as bytes, you can cast the characters to bytes:
byte[] result = new byte[input.Length];
for (int i = 0; i < input.Length; i++)
{
result[i] = (byte)input[i];
}
这篇关于字符串到原始字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!