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, /, *, strict_mode=False)
binascii.a2b_base64(string, /, *, strict_mode=True, ignorechars)

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.

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.

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

Modifié dans la version 3.15.0a5 (unreleased): Added the ignorechars parameter.

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

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

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 wrapcol parameter.

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

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.

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 input sequence is in Adobe Ascii85 format (i.e. is framed with <~ and ~>).

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

Invalid Ascii85 data will raise binascii.Error.

Ajouté dans la version 3.15.0a5 (unreleased).

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 input is padded with b'\0' so its length is a multiple of 4 bytes before encoding. Note that the btoa implementation always pads.

adobe controls whether the encoded byte sequence is framed with <~ and ~>, which is used by the Adobe implementation.

Ajouté dans la version 3.15.0a5 (unreleased).

binascii.a2b_base85(string, /)

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.

Invalid Base85 data will raise binascii.Error.

Ajouté dans la version 3.15.0a5 (unreleased).

binascii.b2a_base85(data, /, *, pad=False)

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

If pad is true, the input is padded with b'\0' so its length is a multiple of 4 bytes before encoding.

Ajouté dans la version 3.15.0a5 (unreleased).

binascii.a2b_z85(string, /)

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

Valid Z85 data contains characters from the Z85 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.

See Z85 specification for more information.

Invalid Z85 data will raise binascii.Error.

Ajouté dans la version 3.15.0a5 (unreleased).

binascii.b2a_z85(data, /, *, pad=False)

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

If pad is true, the input is padded with b'\0' so its length is a multiple of 4 bytes before encoding.

See Z85 specification for more information.

Ajouté dans la version 3.15.0a5 (unreleased).

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)
binascii.unhexlify(hexstr)

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.

Une fonctionnalité similaire (n’acceptant que les arguments de chaîne de texte, mais plus libérale vis-à-vis des espaces blancs) est également accessible en utilisant la méthode de classe bytes.fromhex().

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.

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.