字节[]转换为ASCII

本文关键字:ASCII 转换 字节 | 更新日期: 2023-09-27 18:00:51

我收到了以二进制值返回的文本文件的内容:

Byte[] buf = new Byte[size];
stream = File.InputStream;
stream.Read(buf, 0, size);

如何将其转换为ASCII?

字节[]转换为ASCII

使用:

string str=System.Text.Encoding.ASCII.GetString(buf);

您可以使用:

System.Text.Encoding.ASCII.GetString(buf);

但有时你会得到一个奇怪的数字,而不是你想要的字符串。在这种情况下,当你看到原始字符串时,它可能有一些十六进制字符。如果是这样的话,你可能想试试这个:

System.Text.Encoding.UTF8.GetString(buf);

或者作为最后手段:

System.Text.Encoding.Default.GetString(bytearray);
Encoding.ASCII.GetString(buf);

作为将数据从流读取到字节数组的替代方案,您可以让框架处理所有内容,只需使用带有ASCII编码的StreamReader设置来读取字符串。这样,您就不需要担心获得合适的缓冲区大小或更大的数据大小。

using (var reader = new StreamReader(stream, Encoding.ASCII))
{
    string theString = reader.ReadToEnd();
    // do something with theString
}

Encoding.GetString方法(Byte[](将字节转换为字符串。

在派生类中重写时,将指定字节数组中的所有字节解码为字符串。

命名空间:System.Text
程序集:mscorlib(在mscorlib.dll中(

语法

public virtual string GetString(byte[] bytes)

参数

bytes
    Type: System.Byte[]
    The byte array containing the sequence of bytes to decode.

返回值

类型:System.String
一个字符串,包含对指定的字节序列进行解码的结果。

异常

ArgumentException        - The byte array contains invalid Unicode code points.
ArgumentNullException    - bytes is null.
DecoderFallbackException - A fallback occurred (see Character Encoding in the .NET Framework for complete explanation) or DecoderFallback is set to DecoderExceptionFallback.

备注

如果要转换的数据仅在顺序块中可用(例如从流中读取的数据(或如果数据量大到它需要分成更小的块,应用程序应使用由提供的解码器或编码器GetDecoder方法或GetEncoder方法班

请参阅下的备注Encoding.GetChars获取更多讨论解码技术和考虑。