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 uu or base64 instead. The binascii module contains low-level functions written in C for greater speed that are used by the higher-level modules.
a2b_* functions accept Unicode strings containing only ASCII characters. Other functions only accept bytes-like objects (such as bytes , bytearray and other objects that support the buffer protocol).
Changed in version 3.3: ASCII-only unicode strings are now accepted by the a2b_* functions.
The binascii module defines the following functions:
binascii. a2b_uu ( string ) ¶
Convert a single line of uuencoded data back to binary and return the binary data. Lines normally contain 45 (binary) bytes, except for the last line. Line data may be followed by whitespace.
binascii. b2a_uu ( data , * , backtick = False ) ¶
Convert binary data to a line of ASCII characters, the return value is the converted line, including a newline char. The length of data should be at most 45. If backtick is true, zeros are represented by ‘`’ instead of spaces.
Changed in version 3.7: Added the backtick parameter.
Convert a block of base64 data back to binary and return the binary data. More than one line may be passed at a time.
If strict_mode is true, only valid base64 data will be converted. Invalid base64 data will raise binascii.Error .
Contains only characters from the base64 alphabet.
Contains no excess data after padding (including excess padding, newlines, etc.).
Does not start with a padding.
Changed in version 3.11: Added the strict_mode parameter.
Convert binary data to a line of ASCII characters in base64 coding. The return value is the converted line, including a newline char if newline is true. The output of this function conforms to RFC 3548.
Changed in version 3.6: Added the newline parameter.
Convert a block of quoted-printable data back to binary and return the binary data. More than one line may be passed at a time. If the optional argument header is present and true, underscores will be decoded as spaces.
binascii. b2a_qp ( data , quotetabs = False , istext = True , header = False ) ¶
Convert binary data to a line(s) of ASCII characters in quoted-printable encoding. The return value is the converted line(s). If the optional argument quotetabs is present and true, all tabs and spaces will be encoded. If the optional argument istext is present and true, newlines are not encoded but trailing whitespace will be encoded. If the optional argument header is present and true, spaces will be encoded as underscores per RFC 1522. If the optional argument header is present and false, newline characters will be encoded as well; otherwise linefeed conversion might corrupt the binary data stream.
binascii. crc_hqx ( data , value ) ¶
Compute a 16-bit CRC value of data, starting with value as the initial CRC, and return the result. This uses the CRC-CCITT polynomial x 16 + x 12 + x 5 + 1, often represented as 0x1021. This CRC is used in the binhex4 format.
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:
Changed in version 3.0: The result is always unsigned.
Return the hexadecimal representation of the binary data. Every byte of data is converted into the corresponding 2-digit hex representation. The returned bytes object is therefore twice as long as the length of data.
Similar functionality (but returning a text string) is also conveniently accessible using the bytes.hex() method.
If sep is specified, it must be a single character str or bytes object. It will be inserted in the output after every bytes_per_sep input bytes. Separator placement is counted from the right end of the output by default, if you wish to count from the left, supply a negative bytes_per_sep value.
Changed in version 3.8: The sep and bytes_per_sep parameters were added.
Return the binary data represented by the hexadecimal string hexstr. This function is the inverse of b2a_hex() . hexstr must contain an even number of hexadecimal digits (which can be upper or lower case), otherwise an Error exception is raised.
Similar functionality (accepting only text string arguments, but more liberal towards whitespace) is also accessible using the bytes.fromhex() class method.
exception binascii. Error ¶
Exception raised on errors. These are usually programming errors.
exception binascii. Incomplete ¶
Exception raised on incomplete data. These are usually not programming errors, but may be handled by reading a little more data and trying again.
Support for RFC compliant base64-style encoding in base 16, 32, 64, and 85.
Convert a String to Binary in Python
When a string is converted to binary, it generates a list of binary values representing the original characters. Each character must be iterated over and converted to binary.
This article will discuss some methods to convert a string to its binary representation in Python.
Convert a String to Its Binary Representation in Python Using the format() Function
We use the ord() function that translates the Unicode point of the string to a corresponding integer. The format() function converts an integer to a number in base two using the b binary format.
The complete example code is given below.
Convert a String to Its Binary Representation in Python Using the bytearray Method
A byte array is a set of bytes that may store a list of binary data. Instead of iterating over the string explicitly, we can iterate over a byte sequence. It can be achieved without using the ord() function, but using the bytearray() function.
The complete example code is given below.
Convert a String to Its Binary Representation in Python Using the map() Function
We can also use the map() function in replacement of the format() function. map() convert string to a byte array using the bytearray() function and then use bin to convert the array of bytes in binary representation.
The complete example code is given below.
In Python 3, we must define an encoding scheme like utf-8 ; otherwise, an error will be raised.
Convert a String to Its Binary Representation in Python Using the ASCII Method
In Python 3, utf-8 is the default encoding scheme. But this method will use an ASCII encoding scheme instead of utf-8 . For basic alphanumeric strings, the variations between UTF-8 and ASCII encoding are not noticeable. But they will become significant if we are processing text that incorporates characters that are not part of the ASCII character collection.
Преобразование строки в двоичный файл в Python
В этом посте будет обсуждаться, как преобразовать строку в двоичный файл в Python.
1. Использование format() функция
Идея состоит в том, чтобы использовать ord() Функция для преобразования каждого символа строки в соответствующее целое число, представляющее кодовую точку Unicode этого символа. Затем вы можете передать это целое число в format() функция, которая преобразует его в число по основанию 2, когда b используется двоичный формат.
How to convert string to binary?
I am in need of a way to get the binary representation of a string in python. e.g.
Is there a module of some neat way of doing this?
![]()
9 Answers 9
Something like this?
![]()
If by binary you mean bytes type, you can just use encode method of the string object that encodes your string as a bytes object using the passed encoding type. You just need to make sure you pass a proper encoding to encode function.
Otherwise, if you want them in form of zeros and ones —binary representation— as a more pythonic way you can first convert your string to byte array then use bin function within map :
Or you can join it:
Note that in python3 you need to specify an encoding for bytearray function :
You can also use binascii module in python 2:
hexlify return the hexadecimal representation of the binary data then you can convert to int by specifying 16 as its base then convert it to binary with bin .
![]()
We just need to encode it.
You can access the code values for the characters in your string using the ord() built-in function. If you then need to format this in binary, the string.format() method will do the job.
(Thanks to Ashwini Chaudhary for posting that code snippet.)
While the above code works in Python 3, this matter gets more complicated if you’re assuming any encoding other than UTF-8. In Python 2, strings are byte sequences, and ASCII encoding is assumed by default. In Python 3, strings are assumed to be Unicode, and there’s a separate bytes type that acts more like a Python 2 string. If you wish to assume any encoding other than UTF-8, you’ll need to specify the encoding.
In Python 3, then, you can do something like this:
The differences between UTF-8 and ascii encoding won’t be obvious for simple alphanumeric strings, but will become important if you’re processing text that includes characters not in the ascii character set.