# `binascii` --- 在二进制数据和 ASCII 之间进行转换

`binascii` 模块包含多个方法用来在二进制数据和多种 ASCII 编码的二进制数据表示形式之间进行转换。 在通常情况下，你不会直接使用这些函数而是使用 `base64` 这样的包装器模块作为替代。 `binascii` 模块包含用 C 语言编写的供这些高层级模块使用的低层级函数以获得更快的运行速度。

备注

`a2b_*` 函数接受只含有 ASCII 码的 Unicode 字符串。其他函数只接受 字节型对象 (如 `bytes`，`bytearray` 和其他支持缓冲区协议的对象)。

在 3.3 版本发生变更: ASCII-only unicode strings are now accepted by the `a2b_*` functions.

`binascii` 模块定义了下列函数：

binascii.a2b_uu(string)

  将单行 uu 编码数据转换成二进制数据并返回。uu 编码每行的数据通常包含 45 个（二进制）字节，最后一行除外。每行数据后面可能跟有空格。

binascii.b2a_uu(data, *, backtick=False)

  将二进制数据转换为 ASCII 编码字符，返回值是转换后的行数据，包括换行符。 data 的长度最多为 45。如果 backtick 为 true，则零由 `'`'` 而不是空格表示。

  在 3.7 版本发生变更: 增加 backtick 形参。

binascii.a2b_base64(string, /, *, padded=True, alphabet=BASE64_ALPHABET, strict_mode=False, canonical=False)
binascii.a2b_base64(string, /, *, ignorechars, padded=True, alphabet=BASE64_ALPHABET, strict_mode=True, canonical=False)

  将 base64 数据块转换成二进制并以二进制数据形式返回。一次可以传递多行数据。

  可选的 alphabet 必须是一个长度为 64 的 `bytes` 对象，指定替代字母表。

  If padded is true, the last group of 4 base 64 alphabet characters must be padded with the '=' character. If padded is false, padding is neither required nor recognized: the '=' character is not treated as padding but as a non-alphabet character, which means it is silently discarded when strict_mode is false, or causes an `Error` when strict_mode is true unless b'=' is included in ignorechars.

  If ignorechars is specified, it should be a bytes-like object containing characters to ignore from the input when strict_mode is true. If ignorechars contains the pad character `'='`, the pad characters presented before the end of the encoded data and the excess pad characters will be ignored. The default value of strict_mode is `True` if ignorechars is specified, `False` otherwise.

  如果 strict_mode 为真值，则将只转换有效的 base64 数据。无效的 base64 数据将会引发 `binascii.Error`.

  有效的 base64:

  - 遵循 RFC 4648。

  - 仅包含来自 base64 字符表的字符。

  - 不包含填充后的额外数据（包括冗余填充、换行符等）。

  - 不以填充符打头。

  If canonical is true, non-zero padding bits in the last group are rejected with `binascii.Error`, enforcing canonical encoding as defined in RFC 4648 section 3.5. This check is independent of strict_mode.

  在 3.11 版本发生变更: 增加了 strict_mode 形参。

  在 3.15 版本发生变更: Added the alphabet, canonical, ignorechars, and padded parameters.

binascii.b2a_base64(data, *, padded=True, alphabet=BASE64_ALPHABET, wrapcol=0, newline=True)

  Convert binary data to a line(s) of ASCII characters in base64 coding, as specified in RFC 4648.

  如果 padded 为（默认的）真值，则用 '=' 字符填充已编码数据长度为 4 的倍数。 如果 padded 为假值，则不添加填充字符。

  如果 wrapcol 为非零值，则在至多每 wrapcol 个字符后插入一个换行符 (`b'\n'`)。 如果 wrapcol 为零（默认），则不插入换行符。

  If newline is true (default), a newline character will be added at the end of the output.

  在 3.6 版本发生变更: 增加 newline 形参。

  在 3.15 版本发生变更: Added the alphabet, padded and wrapcol parameters.

binascii.a2b_ascii85(string, /, *, foldspaces=False, adobe=False, ignorechars=b'', canonical=False)

  Convert Ascii85 data back to binary and return the binary data.

  Valid Ascii85 data contains characters from the Ascii85 alphabet in groups of five (except for the final group, which may have from two to five characters). Each group encodes 32 bits of binary data in the range from `0` to `2 ** 32 - 1`, inclusive. The special character `z` is accepted as a short form of the group `!!!!!`, which encodes four consecutive null bytes. A single-character final group is always rejected as an encoding violation.

  foldspaces 旗标指明是否应接受 'y' 短序列作为 4 个连续空格 (ASCII 0x20) 的快捷方式。此特性不被 "标准" Ascii85 编码格式所支持。

  adobe controls whether the encoded byte sequence is framed with `<~` and `~>`, as in a PostScript base-85 string literal. If adobe is true, a leading `<~` is optionally accepted, while a trailing `~>` is required, and `binascii.Error` is raised if it is not found.

  ignorechars should be a bytes-like object containing characters to ignore from the input. This should only contain whitespace characters.

  If canonical is true, non-canonical encodings are rejected with `binascii.Error`. Here "canonical" means the encoding that `b2a_ascii85()` would produce: the `z` abbreviation must be used for all-zero groups (rather than `!!!!!`), and partial final groups must use the same padding digits as the encoder.

  Invalid Ascii85 data will raise `binascii.Error`.

  Added in version 3.15.

binascii.b2a_ascii85(data, /, *, foldspaces=False, wrapcol=0, pad=False, adobe=False)

  Convert binary data to a formatted sequence of ASCII characters in Ascii85 coding. The return value is the converted data.

  foldspaces 是一个可选的标志，使用特殊的短序列 'y' 代替 'btoa' 提供的 4 个连续空格 (ASCII 0x20)。这个特性不被 "标准" Ascii85 编码支持。

  如果 wrapcol 为非零值，则在至多每 wrapcol 个字符后插入一个换行符 (`b'\n'`)。 如果 wrapcol 为零（默认），则不插入换行符。

  If pad is true, the zero-padding applied to the end of the input is fully retained in the output encoding, as done by `btoa`, producing an exact multiple of 5 bytes of output. This is not part of the standard encoding used in PDF, as it does not preserve the length of the data.

  adobe controls whether the encoded byte sequence is framed with `<~` and `~>`, as in a PostScript base-85 string literal. Note that while ASCII85Decode streams in PDF documents must be terminated with `~>`, they must not use a leading `<~`.

  Added in version 3.15.

binascii.a2b_base85(string, /, *, alphabet=BASE85_ALPHABET, ignorechars=b'', canonical=False)

  Convert Base85 data back to binary and return the binary data. More than one line may be passed at a time.

  Valid Base85 data contains characters from the Base85 alphabet in groups of five (except for the final group, which may have from two to five characters). Each group encodes 32 bits of binary data in the range from `0` to `2 ** 32 - 1`, inclusive. A single-character final group is always rejected as an encoding violation.

  Optional alphabet must be a `bytes` object of length 85 which specifies an alternative alphabet.

  ignorechars 应当是一个包含要从输入中忽略的字符的 bytes-like object。

  If canonical is true, non-canonical encodings are rejected with `binascii.Error`. Here "canonical" means the encoding that `b2a_base85()` would produce: partial final groups must use the same padding digits as the encoder.

  Invalid Base85 data will raise `binascii.Error`.

  Added in version 3.15.

binascii.b2a_base85(data, /, *, alphabet=BASE85_ALPHABET, wrapcol=0, pad=False)

  Convert binary data to a line of ASCII characters in Base85 coding. The return value is the converted line.

  Optional alphabet must be a bytes-like object of length 85 which specifies an alternative alphabet.

  如果 wrapcol 为非零值，则在至多每 wrapcol 个字符后插入一个换行符 (`b'\n'`)。 如果 wrapcol 为零（默认），则不插入换行符。

  If pad is true, the zero-padding applied to the end of the input is retained in the output, which will always be a multiple of 5 bytes, and thus the length of the data may not be preserved on decoding.

  Added in version 3.15.

binascii.a2b_base32(string, /, *, padded=True, alphabet=BASE32_ALPHABET, ignorechars=b'', canonical=False)

  Convert base32 data back to binary and return the binary data.

  Valid base32 data contains characters from the base32 alphabet specified in RFC 4648 in groups of eight (if necessary, the final group is padded to eight characters with `=`). Each group encodes 40 bits of binary data in the range from `0` to `2 ** 40 - 1`, inclusive.

  备注

  This function does not map lowercase characters (which are invalid in standard base32) to their uppercase counterparts, nor does it contextually map `0` to `O` and `1` to `I`/`L` as RFC 4648 allows.

  Optional alphabet must be a `bytes` object of length 32 which specifies an alternative alphabet.

  If padded is true, the last group of 8 base 32 alphabet characters must be padded with the '=' character. If padded is false, the '=' character is treated as other non-alphabet characters (depending on the value of ignorechars).

  ignorechars should be a bytes-like object containing characters to ignore from the input. If ignorechars contains the pad character `'='`, the pad characters presented before the end of the encoded data and the excess pad characters will be ignored.

  If canonical is true, non-zero padding bits in the last group are rejected with `binascii.Error`, enforcing canonical encoding as defined in RFC 4648 section 3.5.

  Invalid base32 data will raise `binascii.Error`.

  Added in version 3.15.

binascii.b2a_base32(data, /, *, padded=True, alphabet=BASE32_ALPHABET, wrapcol=0)

  Convert binary data to a line of ASCII characters in base32 coding, as specified in RFC 4648. The return value is the converted line.

  Optional alphabet must be a bytes-like object of length 32 which specifies an alternative alphabet.

  If padded is true (default), pad the encoded data with the '=' character to a size multiple of 8. If padded is false, do not add the pad characters.

  如果 wrapcol 为非零值，则在至多每 wrapcol 个字符后插入一个换行符 (`b'\n'`)。 如果 wrapcol 为零（默认），则不插入换行符。

  Added in version 3.15.

binascii.a2b_qp(data, header=False)

  将一个引号可打印的数据块转换成二进制数据并返回。一次可以转换多行。如果可选参数 header 存在且为 true，则数据中的下划线将被解码成空格。

binascii.b2a_qp(data, quotetabs=False, istext=True, header=False)

  将二进制数据转换为一行或多行带引号可打印编码的 ASCII 字符串。返回值是转换后的行数据。如果可选参数 quotetabs 存在且为真值，则对所有制表符和空格进行编码。如果可选参数 istext 存在且为真值，则不对新行进行编码，但将对尾随空格进行编码。如果可选参数 header 存在且为 true，则空格将被编码为下划线 RFC 1522。如果可选参数 header 存在且为假值，则也会对换行符进行编码;不进行换行转换编码可能会破坏二进制数据流。

binascii.crc_hqx(data, value)

  以 value 作为初始 CRC 计算 data 的 16 位 CRC 值，返回其结果。这里使用 CRC-CCITT 生成多项式 x16 + x12 + x5 + 1，通常表示为 0x1021。该 CRC 被用于 binhex4 格式。

binascii.crc32(data[, value])

  计算 CRC-32，即 data 的无符号 32 位校验和，初始 CRC 值为 value。默认的初始 CRC 值为零。该算法与 ZIP 文件校验和算法一致。由于该算法被设计用作校验和算法，因此不适合用作通用哈希算法。使用方式如下:

      print(binascii.crc32(b"hello world"))
      # 或者，分成两块：
      crc = binascii.crc32(b"hello")
      crc = binascii.crc32(b" world", crc)
      print('crc32 = {:#010x}'.format(crc))

  在 3.0 版本发生变更: 结果将总是不带符号的。

binascii.b2a_hex(data[, sep[, bytes_per_sep=1]])
binascii.hexlify(data[, sep[, bytes_per_sep=1]])

  返回二进制数据 data 的十六进制表示形式。 data 的每个字节都被转换为相应的 2 位十六进制表示形式。因此返回的字节对象的长度是 data 的两倍。

  使用 `bytes.hex()` 方法也可以方便地实现相似的功能（但仅返回文本字符串）。

  如果指定了 sep，它必须为单字符 str 或 bytes 对象。它将被插入每个 bytes_per_sep 输入字节之后。 分隔符位置默认从输出的右端开始计数，如果你希望从左端开始计数，请提供一个负的 bytes_per_sep 值。

      >>> import binascii
      >>> binascii.b2a_hex(b'\xb9\x01\xef')
      b'b901ef'
      >>> binascii.hexlify(b'\xb9\x01\xef', '-')
      b'b9-01-ef'
      >>> binascii.b2a_hex(b'\xb9\x01\xef', b'_', 2)
      b'b9_01ef'
      >>> binascii.b2a_hex(b'\xb9\x01\xef', b' ', -2)
      b'b901 ef'

  在 3.8 版本发生变更: 添加了 sep 和 bytes_per_sep 形参。

binascii.a2b_hex(hexstr, *, ignorechars=b'')
binascii.unhexlify(hexstr, *, ignorechars=b'')

  返回由十六进制字符串 hexstr 表示的二进制数据。此函数功能与 `b2a_hex()` 相反。 hexstr 必须包含偶数个十六进制数字（可以是大写或小写），否则会引发 `Error` 异常。

  ignorechars 应当是一个包含要从输入中忽略的字符的 bytes-like object。

  使用 `bytes.fromhex()` 类方法也可以实现相似的功能（仅接受文本字符串参数，不限制其中的空白字符）。

  在 3.15 版本发生变更: 增加了 ignorechars 形参。

exception binascii.Error

  通常是因为编程错误引发的异常。

exception binascii.Incomplete

  数据不完整引发的异常。通常不是编程错误导致的，可以通过读取更多的数据并再次尝试来处理该异常。

binascii.BASE64_ALPHABET

  The Base 64 alphabet according to RFC 4648.

  Added in version 3.15.

binascii.URLSAFE_BASE64_ALPHABET

  The "URL and filename safe" Base 64 alphabet according to RFC 4648.

  Added in version 3.15.

binascii.UU_ALPHABET

  The uuencoding alphabet.

  Added in version 3.15.

binascii.CRYPT_ALPHABET

  The Base 64 alphabet used in the crypt(3) routine and in the GEDCOM format.

  Added in version 3.15.

binascii.BINHEX_ALPHABET

  The Base 64 alphabet used in BinHex 4 (HQX) within the classic Mac OS.

  Added in version 3.15.

binascii.BASE85_ALPHABET

  Base85 字母表。

  Added in version 3.15.

binascii.ASCII85_ALPHABET

  The Ascii85 字母表。

  Added in version 3.15.

binascii.Z85_ALPHABET

  Z85 字母表。

  Added in version 3.15.

binascii.BASE32_ALPHABET

  基于 RFC 4648 的 Base 32 字母表。

  Added in version 3.15.

binascii.BASE32HEX_ALPHABET

  基于 RFC 4648 "Extended Hex" Base 32 字母表。 使用此字母表解码的数据将在按位比较期间保持及排序。

  Added in version 3.15.

参见

模块 `base64`

  支持符合 RFC 规范的 base16、base32、base64 和 base85 编码。

模块 `quopri`

  支持在 MIME 版本电子邮件中使用引号可打印编码。