Skip to content

Instantly share code, notes, and snippets.

@anaisbetts
Created August 22, 2011 20:34
Show Gist options
  • Select an option

  • Save anaisbetts/1163457 to your computer and use it in GitHub Desktop.

Select an option

Save anaisbetts/1163457 to your computer and use it in GitHub Desktop.
// Is there a BOM of various kinds? (http://en.wikipedia.org/wiki/Byte_order_mark)
var BOMPatterns = new[]
{
new {Pattern = new byte[] {0xEF, 0xBB, 0xFF}, Encoding = Encoding.UTF8},
new {Pattern = new byte[] {0xFE, 0xFF}, Encoding = Encoding.BigEndianUnicode},
new {Pattern = new byte[] {0xFF, 0xFE}, Encoding = Encoding.Unicode},
new {Pattern = new byte[] {0xFF, 0xFE, 0x00, 0x00}, Encoding = Encoding.UTF32},
new {Pattern = new byte[] {0x2B, 0x2F, 0x76, 0x38}, Encoding = Encoding.UTF7},
new {Pattern = new byte[] {0x2B, 0x2F, 0x76, 0x39}, Encoding = Encoding.UTF7},
new {Pattern = new byte[] {0x2B, 0x2F, 0x76, 0x2B}, Encoding = Encoding.UTF7},
new {Pattern = new byte[] {0x2B, 0x2F, 0x76, 0x2F}, Encoding = Encoding.UTF7},
};
var bomDetectedEncoding = BOMPatterns.FirstOrDefault(bom =>
bom.Pattern.Zip(buffer, (l, r) => l == r).All(x => x != false));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment