2011-07-02 30 views
36

我收到的二进制值返回一个文本文件的内容:字节[]为ASCII

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

我怎样才能将它转换为ASCII?

回答

71
+1

它的工作!它也适用于***输入缓冲区的任何子集*** - 使用具有两个额外参数的变体:['ASCIIEncoding.GetString(byte [] bytes,int byteIndex,int byteCount)]](https:// msdn .microsoft.com/en-us/library/38b953c8%28v = vs.110%29.aspx?cs-save-lang = 1&cs-lang = csharp#code-snippet-1)(or without the third parameter for until缓冲区的末尾)。 (您可以在答案中包含这些信息,以获得更全面的答案,但未明确要求。) –

+0

@PeterMortensen:谢谢,欢迎您编辑:) –

3
Encoding.ASCII.GetString(buf); 
3

作为替代从流字节数组读取数据,你可以让框架处理一切,只是使用StreamReader设置了一个ASCII编码在字符串中读取。这样您就不必担心获得适当的缓冲区大小或更大的数据大小。

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

您可以使用:

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

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

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

或者作为最后一招:

System.Text.Encoding.Default.GetString(bytearray); 
1

Encoding.GetString Method (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. 

备注

如果要转换的数据是 仅在连续块 (如从流读出的数据),或者如果 数据量太大,以至于 它需要分成更小的 bl ocks,应用程序应分别使用衍生的 类的 解码器或由编码器提供的 GetDecoder方法或GetEncoder 方法。

请参阅 下的备注Encoding.GetChars关于解码技术的更多讨论 和 的考虑事项。

相关问题