UTF-8和UTF-8与BOM有什么不同?哪个更好?


当前回答

Unicode字节顺序标记(BOM)常见问题解答提供了一个简明的答案:

Q: How I should deal with BOMs? A: Here are some guidelines to follow: A particular protocol (e.g. Microsoft conventions for .txt files) may require use of the BOM on certain Unicode data streams, such as files. When you need to conform to such a protocol, use a BOM. Some protocols allow optional BOMs in the case of untagged text. In those cases, Where a text data stream is known to be plain text, but of unknown encoding, BOM can be used as a signature. If there is no BOM, the encoding could be anything. Where a text data stream is known to be plain Unicode text (but not which endian), then BOM can be used as a signature. If there is no BOM, the text should be interpreted as big-endian. Some byte oriented protocols expect ASCII characters at the beginning of a file. If UTF-8 is used with these protocols, use of the BOM as encoding form signature should be avoided. Where the precise type of the data stream is known (e.g. Unicode big-endian or Unicode little-endian), the BOM should not be used. In particular, whenever a data stream is declared to be UTF-16BE, UTF-16LE, UTF-32BE or UTF-32LE a BOM must not be used.

其他回答

没有BOM的UTF-8没有BOM,这并不意味着它比有BOM的UTF-8更好,除非文件的消费者需要知道(或者从知道中受益)文件是否是UTF-8编码的。

BOM通常用于确定编码的字节序,这对于大多数用例来说是不需要的。

此外,对于那些不了解或不关心BOM的消费者来说,BOM可能是不必要的噪音/痛苦,并可能导致用户困惑。

如果你在HTML文件中使用UTF-8,如果你在同一页面上使用塞尔维亚西里尔语、塞尔维亚拉丁语、德语、匈牙利语或一些外来语言,那么使用UTF和BOM更好。

这是我(从事计算机和IT行业30年)的观点。

只有当文件实际包含一些非ascii字符时,UTF-8和BOM才有用。如果包含了它,而没有任何ASCII,那么它可能会破坏旧的应用程序,否则将文件解释为纯ASCII。当遇到非ASCII字符时,这些应用程序肯定会失败,因此在我看来,只有当文件可以并且不应该再被解释为纯ASCII时,才应该添加BOM。

我想说清楚的是,我宁愿没有BOM。如果一些旧的垃圾没有它就坏了,那么就添加它,替换遗留应用程序是不可行的。

不要制作UTF-8的BOM之外的任何东西。

UTF-8 BOM是文本流开头的字节序列(0xEF, 0xBB, 0xBF),它允许读者更可靠地猜测文件是否以UTF-8编码。

通常,BOM用于表示编码的字节顺序,但由于字节顺序与UTF-8无关,因此BOM是不必要的。

根据Unicode标准,不建议使用UTF-8文件的BOM:

2.6编码方案 ... 对于UTF-8,既不要求也不建议使用BOM,但在将UTF-8数据从使用BOM的其他编码形式转换或将BOM用作UTF-8签名的上下文中可能会遇到这种情况。有关更多信息,请参阅第16.8节特殊项中的“字节顺序标记”小节。

应该注意的是,对于某些文件,即使在Windows上也不能有BOM。例如SQL*plus或VBScript文件。如果这样的文件包含BOM,则在尝试执行它们时会出现错误。