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

Nota:

  Las funciones "a2b_*" aceptan cadenas Unicode que contienen solo
  caracteres ASCII. Otras funciones solo aceptan *objetos tipo
  binarios* (como "bytes", "bytearray" y otros objetos que admiten el
  protocolo de búfer).

  Distinto en la versión 3.3: Las cadenas unicode con sólo caracteres
  ASCII son ahora aceptadas por las funciones "a2b_*".

The "binascii" module defines the following functions:

binascii.a2b_uu(string)

   Convierte una sola línea de datos uuencoded de nuevo a binarios y
   retorna los datos binarios. Las líneas normalmente contienen 45
   bytes (binarios), excepto por la última línea. Los datos de línea
   pueden ir seguidos de espacios en blanco.

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

   Convierte datos binarios a una línea de caracteres ASCII, el valor
   retornado es la línea convertida, incluido un carácter de nueva
   línea. La longitud de *data* debe ser como máximo 45. Si *backtick*
   es verdadero, los ceros se representan mediante "'`'" en lugar de
   espacios.

   Distinto en la versión 3.7: Se ha añadido el parámetro *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)

   Convierte un bloque de datos en base64 de nuevo a binario y retorna
   los datos binarios. Se puede pasar más de una línea a la vez.

   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.

   Si *strict_mode* es verdadero, solo se convertirán los datos en
   base64 válidos. Los datos en base64 no válidos lanzarán
   "binascii.Error".

   base64 válido:

   * Conforms to **RFC 4648**.

   * Contiene solo caracteres del alfabeto base64.

   * No contiene exceso de datos después del relleno (incluye el
     exceso de relleno, nuevas líneas, etc.).

   * No empieza con un relleno.

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

   Distinto en la versión 3.11: Se ha añadido el parámetro
   *strick_mode*.

   Distinto en la versión 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.

   Distinto en la versión 3.6: Se ha añadido el parámetro *newline*.

   Distinto en la versión 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".

   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* 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 "<~".

   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* 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".

   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.

   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.

   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.

   Nota:

     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.

   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.

   Added in version 3.15.

binascii.a2b_qp(data, header=False)

   Convierte un bloque de datos imprimibles entre comillas a binario y
   retorna los datos binarios. Se puede pasar más de una línea a la
   vez. Si el argumento opcional *header* está presente y es
   verdadero, los guiones bajos se decodificarán como espacios.

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

   Convierte datos binarios en una(s) línea(s) de caracteres ASCII en
   codificación imprimible entre comillas. El valor de retorno son las
   líneas convertidas. Si el argumento opcional *quotetabs* está
   presente y es verdadero, se codificarán todas los tabs y espacios.
   Si el argumento opcional *istext* está presente y es verdadero, las
   nuevas líneas no se codifican, pero se codificarán los espacios en
   blanco finales. Si el argumento opcional *header* está presente y
   es verdadero, los espacios se codificarán como guiones bajos por:
   rfc: *1522*. Si el argumento opcional *header* está presente y es
   falso, los caracteres de nueva línea también se codificarán; de lo
   contrario, la conversión de salto de línea podría dañar el flujo de
   datos binarios.

binascii.crc_hqx(data, value)

   Calcula un valor CRC de 16 bits de *data*, comenzando con *value*
   como el CRC inicial, y retorna el resultado. Utiliza el polinomio
   CRC-CCITT *x*^16 + *x*^12 + *x*^5 + 1, a menudo representado como
   0x1021. Este CRC se utiliza en el formato binhex4.

binascii.crc32(data[, value])

   Calcula CRC-32, la suma de comprobación de 32 bits de *data* que no
   tiene signo, comenzando con un CRC inicial de *value*. El CRC
   inicial predeterminado es cero. El algoritmo es consistente con la
   suma de verificación del archivo ZIP. Dado que el algoritmo está
   diseñado para usarse como un algoritmo de suma de verificación, no
   es adecuado para usarlo como algoritmo hash general. Úselo de la
   siguiente manera:

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

   Distinto en la versión 3.0: El resultado siempre es sin signo.

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

   Retorna la representación hexadecimal del binario *data*. Cada byte
   de *data* se convierte en la representación hexadecimal de 2
   dígitos correspondiente. Por lo tanto, el objeto de bytes retornado
   es el doble de largo que la longitud de *data*.

   Una funcionalidad similar (pero que retorna una cadena de texto)
   también es convenientemente accesible usando el método
   "bytes.hex()".

   Si se especifica *sep*, debe ser un solo carácter *str* o un objeto
   de bytes. Se insertará en la salida después de cada *bytes_per_sep*
   bytes de entrada . La ubicación del separador se cuenta desde el
   extremo derecho de la salida de forma predeterminada; si desea
   contar desde el izquierdo, proporcione un valor negativo
   *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'

   Distinto en la versión 3.8: Se agregaron los parámetros *sep* y
   *bytes_per_sep*.

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

   Retorna los datos binarios representados por la cadena hexadecimal
   *hexstr*.  Esta función es la inversa de "b2a_hex()". *hexstr* debe
   contener un número par de dígitos hexadecimales (que pueden ser
   mayúsculas o minúsculas), de lo contrario se produce una excepción
   "Error".

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

   Distinto en la versión 3.15: Added the *ignorechars* parameter.

exception binascii.Error

   Excepción provocada por errores. Estos suelen ser errores de
   programación.

exception binascii.Incomplete

   Excepción provocada por datos incompletos. Por lo general, estos no
   son errores de programación, pero se pueden controlar leyendo un
   poco más de datos e intentándolo de nuevo.

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

   The Base85 alphabet.

   Added in version 3.15.

binascii.ASCII85_ALPHABET

   The Ascii85 alphabet.

   Added in version 3.15.

binascii.Z85_ALPHABET

   The Z85 alphabet.

   Added in version 3.15.

binascii.BASE32_ALPHABET

   The Base 32 alphabet according to **RFC 4648**.

   Added in 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.

   Added in version 3.15.

Ver también:

  Módulo "base64"
     Soporte para compatibilidad con RFC de codificación de estilo
     base64 en base 16, 32, 64 y 85.

  Módulo "quopri"
     Soporte para codificación imprimible entre comillas utilizada en
     mensajes de correo electrónico MIME.
