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


当前回答

以下是我使用Visual Studio、Sourcetree和Bitbucket拉请求的经验,这给了我一些问题:

因此,在审查拉取请求时,带有签名的BOM将在每个文件上包含一个红点字符(这可能非常烦人)。

如果你把鼠标停在上面,它会显示一个像“ufeff”这样的字符,但事实证明Sourcetree不显示这些类型的字节标记,所以它很可能会在你的拉请求中结束,这应该是可以的,因为这是Visual Studio 2017现在编码新文件的方式,所以也许Bitbucket应该忽略这个或让它以另一种方式显示,更多信息在这里:

红点标记BitBucket差异视图

其他回答

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节特殊项中的“字节顺序标记”小节。

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

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

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

将BOM放在UTF-8编码的文件中至少有三个问题。

不包含文本的文件不再为空,因为它们始终包含BOM。 在UTF-8的ASCII子集中保存文本的文件本身不再是ASCII,因为BOM不是ASCII,这使得一些现有工具无法使用,用户可能不可能替换这些遗留工具。 不可能将几个文件连接在一起,因为现在每个文件开头都有一个BOM。

而且,正如其他人所提到的,使用BOM来检测某些东西是否是UTF-8是既不够也没有必要的:

这是不够的,因为任意字节序列可能恰好以构成BOM的确切序列开始。 这是不必要的,因为你可以像读取UTF-8一样读取字节;如果成功,根据定义,它是有效的UTF-8。

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.