# `binascii` --- Convert between binary and ASCII

The `binascii` module contains a number of methods to convert between binary and various ASCII-encoded binary representations. Normally, you will not use these functions directly but use wrapper modules like `base64` instead. The `binascii` module contains low-level functions written in C for greater speed that are used by the higher-level modules.

Note

La fonction `a2b_*` accepte des chaînes de caractères contenant seulement des caractères ASCII. D’autres fonctions acceptent seulement des objets bytes et similaire (tel que `bytes`, `bytearray` et autres objets qui supportent le protocole tampon).

Modifié dans la version 3.3: Les chaines de caractères unicode seulement composées de caractères ASCII sont désormais acceptées par les fonctions `a2b_*`.

The `binascii` module defines the following functions:

binascii.a2b_uu(string)

  Convertit une seule ligne de donnée uuencoded en binaire et renvoie la donnée binaire. Les lignes contiennent normalement 45 octets (binaire), sauf pour la dernière ligne. Il se peut que la ligne de donnée soit suivie d’un espace blanc.

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

  Convertit les données binaires en une ligne de caractères ASCII, la valeur renvoyée est la ligne convertie incluant un caractère de nouvelle ligne. La longueur de data doit être au maximum de 45. Si backtick est vraie, les zéros sont représentés par `'`'` plutôt que par des espaces.

  Modifié dans la version 3.7: Ajout du paramètre 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)

  Convertit un bloc de donnée en base64 en binaire et renvoie la donnée binaire. Plus d’une ligne peut être passé à la fois.

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

  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.

  If strict_mode is true, only valid base64 data will be converted. Invalid base64 data will raise `binascii.Error`.

  Valid base64:

  - Conforms to RFC 4648.

  - Contains only characters from the base64 alphabet.

  - Contains no excess data after padding (including excess padding, newlines, etc.).

  - Does not start with a padding.

  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.

  Modifié dans la version 3.11: Added the strict_mode parameter.

  Modifié dans la version 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.

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

  If wrapcol is non-zero, insert a newline (`b'\n'`) character after at most every wrapcol characters. If wrapcol is zero (default), do not insert any newlines.

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

  Modifié dans la version 3.6: Ajout du paramètre newline.

  Modifié dans la version 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 is a flag that specifies whether the 'y' short sequence should be accepted as shorthand for 4 consecutive spaces (ASCII 0x20). This feature is not supported by the "standard" Ascii85 encoding.

  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`.

  Ajouté dans la 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 is an optional flag that uses the special short sequence 'y' instead of 4 consecutive spaces (ASCII 0x20) as supported by 'btoa'. This feature is not supported by the "standard" Ascii85 encoding.

  If wrapcol is non-zero, insert a newline (`b'\n'`) character after at most every wrapcol characters. If wrapcol is zero (default), do not insert any newlines.

  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 `<~`.

  Ajouté dans la 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 should be a bytes-like object containing characters to ignore from the input.

  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`.

  Ajouté dans la 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.

  If wrapcol is non-zero, insert a newline (`b'\n'`) character after at most every wrapcol characters. If wrapcol is zero (default), do not insert any newlines.

  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.

  Ajouté dans la 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.

  Note

  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`.

  Ajouté dans la 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.

  If wrapcol is non-zero, insert a newline (`b'\n'`) character after at most every wrapcol characters. If wrapcol is zero (default), do not insert any newlines.

  Ajouté dans la version 3.15.

binascii.a2b_qp(data, header=False)

  Convertit un bloc de données quoted-printable en binaire et renvoie les données binaires. Plus d’une ligne peut être passée à la fois. Si l’argument optionnel header est présent et vrai, les traits soulignés seront décodés en espaces.

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

  Convertit les données binaires en ligne(s) de caractères ASCII en codage imprimable entre guillemets. La valeur de retour est lales lignes(s) convertie(s). Si l’argument optionnel quotetabs est présent et vrai, toutes les tabulations et espaces seront encodés. Si l’argument optionnel istext est présent et faux, les nouvelles lignes ne sont pas encodées mais les espaces de fin de ligne le seront. Si l’argument optionnel header est présent et vrai, les espaces vont être encodés comme de traits soulignés selon RFC 1522. Si l’argument optionnel header est présent et faux, les caractères de nouvelle ligne seront également encodés ; sinon la conversion de saut de ligne pourrait corrompre le flux de données binaire.

binascii.crc_hqx(data, value)

  Calcule une valeur en CRC 16-bit de data, commençant par value comme CRC initial et renvoie le résultat. Ceci utilise le CRC-CCITT polynomial x16 + x12 + x5 + 1, souvent représenté comme 0x1021. Ce CRC est utilisé dans le format binhex4.

binascii.crc32(data[, value])

  Compute CRC-32, the unsigned 32-bit checksum of data, starting with an initial CRC of value. The default initial CRC is zero. The algorithm is consistent with the ZIP file checksum. Since the algorithm is designed for use as a checksum algorithm, it is not suitable for use as a general hash algorithm. Use as follows:

      print(binascii.crc32(b"hello world"))
      # Or, in two pieces:
      crc = binascii.crc32(b"hello")
      crc = binascii.crc32(b" world", crc)
      print('crc32 = {:#010x}'.format(crc))

  Modifié dans la version 3.0: Renvoie une valeur non-signée.

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

  Renvoie la représentation hexadécimale du binaire data. Chaque octet de data est converti en la représentation 2 chiffres correspondante. L’objet octets renvoyé est donc deux fois plus long que la longueur de data.

  Fonctionnalité similaire est également commodément accessible en utilisant la méthode `bytes.hex()`.

  Si sep est spécifié, il doit s'agir d'une chaîne de caractères ou d'un objet byte. Il sera inséré dans la sortie tous les bytes_per_sep octets. Par défaut, l'emplacement du séparateur est compté à partir de l'extrémité droite de la sortie. Si vous souhaitez compter à partir de la gauche, indiquez une valeur bytes_per_sep négative.

      >>> 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'

  Modifié dans la version 3.8: ajout des paramètres sep et bytes_per_sep.

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

  Renvoie la donnée binaire représentée par la chaîne de caractères hexadécimale hexstr. Cette fonction est l’inverse de `b2a_hex()`. hexstr doit contenir un nombre pair de chiffres hexadécimaux (qui peuvent être en majuscule ou minuscule), sinon une exception `Error` est levée.

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

  Similar functionality (but more liberal towards whitespace) is also accessible using the `bytes.fromhex()` class method.

  Modifié dans la version 3.15: Added the ignorechars parameter.

exception binascii.Error

  Exception levée en cas d'erreurs. Ce sont typiquement des erreurs de programmation.

exception binascii.Incomplete

  Exception levée par des données incomplète. Il ne s’agit généralement pas d’erreurs de programmation, mais elles peuvent être traitées en lisant un peu plus de données et en réessayant.

binascii.BASE64_ALPHABET

  The Base 64 alphabet according to RFC 4648.

  Ajouté dans la version 3.15.

binascii.URLSAFE_BASE64_ALPHABET

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

  Ajouté dans la version 3.15.

binascii.UU_ALPHABET

  The uuencoding alphabet.

  Ajouté dans la version 3.15.

binascii.CRYPT_ALPHABET

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

  Ajouté dans la version 3.15.

binascii.BINHEX_ALPHABET

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

  Ajouté dans la version 3.15.

binascii.BASE85_ALPHABET

  The Base85 alphabet.

  Ajouté dans la version 3.15.

binascii.ASCII85_ALPHABET

  The Ascii85 alphabet.

  Ajouté dans la version 3.15.

binascii.Z85_ALPHABET

  The Z85 alphabet.

  Ajouté dans la version 3.15.

binascii.BASE32_ALPHABET

  The Base 32 alphabet according to RFC 4648.

  Ajouté dans la version 3.15.

binascii.BASE32HEX_ALPHABET

  The "Extended Hex" Base 32 alphabet according to RFC 4648. Data encoded with this alphabet maintains its sort order during bitwise comparisons.

  Ajouté dans la version 3.15.

Voir aussi

Module `base64`

  Support de l’encodage base64-style conforme RFC en base 16, 32, 64 et 85.

Module `quopri`

  Support de l’encodage quote-printable utilisé par les messages email MIME.