八进制、十六进制、Unicode

Octal, Hex, Unicode

我有一个字符出现在具有十六进制值和八进制值 \xb11.

的线上

这是我的 header 的样子:

From: "1Central Station <sip@...>"

ASCII table图中的字符是"±":

不明白的地方:

  1. 如果我尝试通过在 header 中传递“±Central Station”来进行测试,我会看到它已转换为“\xC2\xB1”。为什么?
  2. 如何让“\xB1”或“1”出现在网络上而不是“\xC2\xB1”。 e.如果我尝试打印“\xB1”或“1”,我永远不会看到“±”被打印出来。但是如果我打印“\u00b1”它会打印所需的字符,我假设是因为“\u00b1”是 Unicode 格式。

从您链接到的页面:

The extended ASCII codes (character code 128-255)

There are several different variations of the 8-bit ASCII table. The table below is according to ISO 8859-1, also called ISO Latin-1.

值得读两遍。字符代码 128–255 不是 ASCII(ASCII 是 7 位编码,以 127 结尾)。

假设您认为所讨论的字符是 ± 是正确的(这很可能,但不能保证),您的文本可以编码为 ISO 8850-1 或者,正如@muistooshort 在注释,许多其他 ISO 8859-X or CP-12XX (Windows-12XX) 编码中的任何一种。但是,我们确实知道文本不是(有效的)UTF-8,因为 0xb1 本身不是有效的 UTF-8 字符。

如果幸运的话,无论客户端发送此文本都在 Content-Type header.

中指定了编码

关于您的问题:

  1. If I try to test the same by passing ±Central Station in header I see it get converted to \xC2\xB1. Why?

您传递的文本是 UTF-8 格式的,在 UTF-8 中表示 ± 的字节是 0xC2 0xB1.

  1. How can I have \xB1 or 1 appearing over the wire instead of \xC2\xB1?

我们不知道你是如何测试这个的,所以我们无法回答这个问题。不过,一般来说:要么发送编码为 ISO 8859-1 的文本(Ruby 中的 Encoding::ISO_8859_1),要么发送原始文本所采用的任何编码,或者作为原始字节(Encoding::ASCII_8BITEncoding::BINARY, 互为别名).

  1. If I try to print \xB1 or 1 I never see ± being printed. But if I print \u00b1 it prints the desired character. (I'm assuming because \u00b1 is the unicode format but I will love If some can explain this in detail.)

这不是问题,但原因是 \xB1 (1) 不是有效的 UTF-8 字符。有些接口会打印 用于无效字符;其他人会简单地忽略它们。另一方面,\u00b1 是一个有效的 Unicode 代码点,Ruby 知道如何用 UTF-8 表示。

简要说明:UTF-8(与 UTF-16 和 UTF-32 一样)是 Unicode 标准指定的字符编码。 U+00B1± 的 Unicode 代码点,0xC2 0xB1 是表示 UTF-8 中该代码点的字节。在 Ruby 中,我们可以使用 Unicode 代码点(\u00b1)或 UTF-8 字节(十六进制:\xC2\xB1;或八进制:21)来表示 UTF-8 字符,虽然我不推荐后者,因为很少 Rubyists 熟悉它)。

字符编码是一个很大的话题,远远超出了 Stack Overflow 答案的范围。要获得一本好的入门书,请阅读 Joel Spolsky 的 "The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)", and for more details on how character encoding works in Ruby read Yehuda Katz's "Encodings, Unabridged"。阅读这两本书将花费您不到 30 分钟的时间,并将在未来为您节省数百小时的痛苦。