C#将字符串转换为字节数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16072709/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting string to byte array in C#
提问by nouptime
I'm converting something from VB into C#. Having a problem with the syntax of this statement:
我正在将一些东西从 VB 转换成 C#。此语句的语法有问题:
if ((searchResult.Properties["user"].Count > 0))
{
profile.User = System.Text.Encoding.UTF8.GetString(searchResult.Properties["user"][0]);
}
I then see the following errors:
然后我看到以下错误:
Argument 1: cannot convert from 'object' to 'byte[]'
The best overloaded method match for 'System.Text.Encoding.GetString(byte[])' has some invalid arguments
参数 1:无法从“对象”转换为“字节[]”
'System.Text.Encoding.GetString(byte[])' 的最佳重载方法匹配有一些无效参数
I tried to fix the code based on thispost, but still no success
我试图根据这篇文章修复代码,但仍然没有成功
string User = Encoding.UTF8.GetString("user", 0);
Any suggestions?
有什么建议?
回答by Timothy Randall
If you already have a byte array then you will need to know what type of encoding was used to make it into that byte array.
如果您已经有一个字节数组,那么您将需要知道使用什么类型的编码将其放入该字节数组中。
For example, if the byte array was created like this:
例如,如果字节数组是这样创建的:
byte[] bytes = Encoding.ASCII.GetBytes(someString);
You will need to turn it back into a string like this:
您需要将其转回这样的字符串:
string someString = Encoding.ASCII.GetString(bytes);
If you can find in the code you inherited, the encoding used to create the byte array then you should be set.
如果您可以在继承的代码中找到用于创建字节数组的编码,那么您应该设置。
回答by Eran Yogev
static byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
static string GetString(byte[] bytes)
{
char[] chars = new char[bytes.Length / sizeof(char)];
System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
return new string(chars);
}
回答by user4726577
A refinement to JustinStolle's edit (Eran Yogev's use of BlockCopy).
对 JustinStolle 编辑的改进(Eran Yogev 对 BlockCopy 的使用)。
The proposed solution is indeed faster than using Encoding. Problem is that it doesn't work for encoding byte arrays of uneven length. As given, it raises an out-of-bound exception. Increasing the length by 1 leaves a trailing byte when decoding from string.
所提出的解决方案确实比使用编码更快。问题是它不适用于编码长度不均匀的字节数组。正如给定的,它引发了一个越界异常。从字符串解码时,将长度增加 1 会留下一个尾随字节。
For me, the need came when I wanted to encode from DataTableto JSON.
I was looking for a way to encode binary fields into strings and decode from string back to byte[].
对我来说,当我想从DataTable到编码时就需要了JSON。我正在寻找一种将二进制字段编码为字符串并从字符串解码回byte[].
I therefore created two classes - one that wraps the above solution (when encoding from strings it's fine, because the lengths are always even), and another that handles byte[]encoding.
因此,我创建了两个类 - 一个包含上述解决方案(从字符串编码时很好,因为长度总是偶数),另一个处理byte[]编码。
I solved the uneven length problem by adding a single character that tells me if the original length of the binary array was odd ('1') or even ('0')
我通过添加一个字符来解决不均匀长度问题,该字符告诉我二进制数组的原始长度是奇数 ('1') 还是偶数 ('0')
As follows:
如下:
public static class StringEncoder
{
static byte[] EncodeToBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
static string DecodeToString(byte[] bytes)
{
char[] chars = new char[bytes.Length / sizeof(char)];
System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
return new string(chars);
}
}
public static class BytesEncoder
{
public static string EncodeToString(byte[] bytes)
{
bool even = (bytes.Length % 2 == 0);
char[] chars = new char[1 + bytes.Length / sizeof(char) + (even ? 0 : 1)];
chars[0] = (even ? '0' : '1');
System.Buffer.BlockCopy(bytes, 0, chars, 2, bytes.Length);
return new string(chars);
}
public static byte[] DecodeToBytes(string str)
{
bool even = str[0] == '0';
byte[] bytes = new byte[(str.Length - 1) * sizeof(char) + (even ? 0 : -1)];
char[] chars = str.ToCharArray();
System.Buffer.BlockCopy(chars, 2, bytes, 0, bytes.Length);
return bytes;
}
}
回答by alireza amini
use this
用这个
byte[] myByte= System.Text.ASCIIEncoding.Default.GetBytes(myString);
回答by Shridhar
First of all, add the System.Textnamespace
首先,添加System.Text命名空间
using System.Text;
Then use this code
然后使用此代码
string input = "some text";
byte[] array = Encoding.ASCII.GetBytes(input);
Hope to fix it!
希望能修好!
回答by Mandar Sudame
The following approach will work only if the chars are 1 byte. (Default unicode will not work since it is 2 bytes)
仅当字符为 1 个字节时,以下方法才有效。(默认 unicode 将不起作用,因为它是 2 个字节)
public static byte[] ToByteArray(string value)
{
char[] charArr = value.ToCharArray();
byte[] bytes = new byte[charArr.Length];
for (int i = 0; i < charArr.Length; i++)
{
byte current = Convert.ToByte(charArr[i]);
bytes[i] = current;
}
return bytes;
}
Keeping it simple
保持简单
回答by Lomithrani
Does anyone see any reason why not to do this?
有没有人看到不这样做的任何理由?
mystring.Select(Convert.ToByte).ToArray()
回答by Ali
Also you can use an Extension Methodto add a method to the stringtype as below:
您也可以使用扩展方法向string类型添加方法,如下所示:
static class Helper
{
public static byte[] ToByteArray(this string str)
{
return System.Text.Encoding.ASCII.GetBytes(str);
}
}
And use it like below:
并像下面这样使用它:
string foo = "bla bla";
byte[] result = foo.ToByteArray();
回答by Kuganrajh Rajendran
var result = System.Text.Encoding.Unicode.GetBytes(text);
回答by Algemist
This question has been answered sufficiently many times, but with C# 7.2 and the introduction of the Span type, there is a faster way to do this in unsafe code:
这个问题已经回答了很多次了,但是随着 C# 7.2 和 Span 类型的引入,有一种更快的方法可以在不安全的代码中做到这一点:
public static class StringSupport
{
private static readonly int _charSize = sizeof(char);
public static unsafe byte[] GetBytes(string str)
{
if (str == null) throw new ArgumentNullException(nameof(str));
if (str.Length == 0) return new byte[0];
fixed (char* p = str)
{
return new Span<byte>(p, str.Length * _charSize).ToArray();
}
}
public static unsafe string GetString(byte[] bytes)
{
if (bytes == null) throw new ArgumentNullException(nameof(bytes));
if (bytes.Length % _charSize != 0) throw new ArgumentException($"Invalid {nameof(bytes)} length");
if (bytes.Length == 0) return string.Empty;
fixed (byte* p = bytes)
{
return new string(new Span<char>(p, bytes.Length / _charSize));
}
}
}
Keep in mind that the bytes represent a UTF-16 encoded string (called "Unicode" in C# land).
请记住,字节表示 UTF-16 编码的字符串(在 C# 中称为“Unicode”)。
Some quick benchmarking shows that the above methods are roughly 5x faster than their Encoding.Unicode.GetBytes(...)/GetString(...) implementations for medium sized strings (30-50 chars), and even faster for larger strings. These methods also seem to be faster than using pointers with Marshal.Copy(..) or Buffer.MemoryCopy(...).
一些快速基准测试表明,对于中等大小的字符串(30-50 个字符),上述方法比它们的 Encoding.Unicode.GetBytes(...)/GetString(...) 实现大约快 5 倍,对于较大的字符串甚至更快。这些方法似乎也比使用 Marshal.Copy(..) 或 Buffer.MemoryCopy(...) 的指针更快。

