c#和Encoding.ASCII.GetString

byte[] header = new byte[]{255, 216}; string ascii = Encoding.ASCII.GetString(header); 

我希望ASCII等于FFD8(JPEG SOI标记)

相反,我得到“????”

在这种情况下,您最好比较字节数组而不是转换为字符串。

如果你必须转换为字符串,我建议使用编码Latin-1 aka ISO-8859-1 aka Code Page 28591编码,因为这个编码会将所有带hex值的字节映射到0到25​​6之间的Unicode字符。相同的hex值 – 方便此方案。 以下任何一种都将获得此编码:

 Encoding.GetEncoding(28591) Encoding.GetEncoding("Latin1") Encoding.GetEncoding("ISO-8859-1") 

是的,那是因为ASCII只有7位 – 它没有定义任何高于127的值。编码通常将未知的二进制值解码为’?’ (尽管可以使用DecoderFallback进行更改)。

如果你要提到“扩展ASCII”我怀疑你真的想要Encoding.Default这是“操作系统的默认代码页”……大多数西方系统的代码页1252 ,我相信。

你期待什么角色?

编辑:根据接受的答案(我怀疑问题是在我添加答案之后编辑的;我不记得看到有关JPEG的任何内容)你不应该将二进制数据转换为文本,除非它是真正编码的文本数据。 JPEG数据是二进制数据 – 因此您应该根据预期的字节检查实际字节。

任何时候使用“普通”文本编码(如ASCII,UTF-8等)将任意二进制数据(如图像,音乐或video)转换为文本,都可能导致数据丢失。 如果您必须将其转换为文本,请使用Base64,这是一个很好的和安全的。 但是,如果您只想将其与预期的二进制数据进行比较,则最好不要将其转换为文本。

编辑:好的,这是一个帮助给定字节数组的图像检测方法的类。 我还没有特定于HTTP; 我不完全确定你是否应该真正获取InputStream ,只读它一点,然后再次获取流。 我坚持使用字节数组来解决这个问题:)

 using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; public sealed class SignatureDetector { public static readonly SignatureDetector Png = new SignatureDetector(0x89, 0x50, 0x4e, 0x47); public static readonly SignatureDetector Bmp = new SignatureDetector(0x42, 0x4d); public static readonly SignatureDetector Gif = new SignatureDetector(0x47, 0x49, 0x46); public static readonly SignatureDetector Jpeg = new SignatureDetector(0xff, 0xd8); public static readonly IEnumerable Images = new ReadOnlyCollection(new[]{Png, Bmp, Gif, Jpeg}); private readonly byte[] bytes; public SignatureDetector(params byte[] bytes) { if (bytes == null) { throw new ArgumentNullException("bytes"); } this.bytes = (byte[]) bytes.Clone(); } public bool Matches(byte[] data) { if (data == null) { throw new ArgumentNullException("data"); } if (data.Length < bytes.Length) { return false; } for (int i=0; i < bytes.Length; i++) { if (data[i] != bytes[i]) { return false; } } return true; } // Convenience method public static bool IsImage(byte[] data) { return Images.Any(detector => detector.Matches(data)); } } 

如果你然后写道:

 Console.WriteLine(ascii) 

并期望打印出“FFD8”,这不是GetString的工作方式。 为此,您需要:

  string ascii = String.Format("{0:X02}{1:X02}", header[0], header[1]); 

我曾写过一个自定义编码器/解码器,它将字节0-255编码为unicode字符0-255并再次返回。

它只对在实际上不是字符串的东西上使用字符串函数非常有用。

你确定吗 ”????” 结果呢?

结果是什么:

 (int)ascii[0] (int)ascii[1] 

另一方面,纯ASCII仅为0-127 ……