- How to convert string to binary in Python(4 ways)
- 1. Using ord(),format() to convert string to binary
- Python Program to Convert string to binary in Python
- Python Program to convert string to binary in Python
- 3. Map() to convert string to binary in Python
- Python Program to convert string to binary in Python
- 4. Math Module,ord(),bin() to convert string to binary
- Python Program to convert string to binary
- Summary
- binascii — Convert between binary and ASCII¶
- Python | Convert String to Binary
- Python3
- Python3
How to convert string to binary in Python(4 ways)
In this post,we are going to learn how to convert string to binary in Python with examples using built in function join() ,ord() ,format() and bytearray(),map(),bin() and Math module.
1. Using ord(),format() to convert string to binary
In this example, we are using three functions join(), ord(), format() to convert string to its binary representation and for loop to iterate over each character of the string, format() function to insert a value between placeholder finally using join() function to concatenate the element by space delimiter.
- ord() : This function returns the number representing the unicode of given character. It takes a string as an argument and returns its unicode
- format() : The format() function format the given value and insert the value between the placeholder.
- Join() : The join() method concatenate the elements by delimiter.
Python Program to Convert string to binary in Python
- val: The number that we want to convert into binary string
- Format : It convert the passed value to given format.
The join() function concatenate the element by space delimiter. Let us understand with an example.
Python Program to convert string to binary in Python
In this example, we have defined a custom method str_binary() that takes a string as an argument and returns binary representation.
def str_binary(Str): binaryStr = ' '.join(format(i, '08b') for i in bytearray(Str, encoding ='utf-8')) print(binaryStr) Str = "Good Morning" str_binary(Str)
01000111 01101111 01101111 01100100 00100000 01001101 01101111 01110010 01101110 01101001 01101110 01100111
3. Map() to convert string to binary in Python
In this example, we are using the bytearray that returns an array of the byte in our example its returns an array of bytes for a given string “str”, using map() along with bin() to get the binary of given string.
Python Program to convert string to binary in Python
def str_binary(Str): binaryStr = ' '.join(map(bin, bytearray(Str, encoding ='utf-8'))) print(bytearray(Str, encoding ='utf-8')) print(binaryStr) Str = "Good Morning" str_binary(Str)
0b1000111 0b1101111 0b1101111 0b1100100 0b100000 0b1001101 0b1101111 0b1110010 0b1101110 0b1101001 0b1101110 0b1100111
4. Math Module,ord(),bin() to convert string to binary
In this example we have defined a custom function name “Strto_Binary” first, we are using ord() to get numbers that represent Unicode of given characters in a string and append them to a list.
In the second step, we are using bin() to get the binary value of each character and [2:] to remove the prefix “0b” and appending them to result in the list(mod_list) and return the result list. We are calling the custom function “Strto_Binary” bypassing the string that we want to convert into binary.
Python Program to convert string to binary
def Strto_Binary(str): list,mod_list=[],[] for item in Str: list.append(ord(item)) for item in list: mod_list.append(int(bin(item)[2:])) return mod_list print(Strto_Binary("Good Morning"))
[1000111, 1101111, 1101111, 1100100, 100000, 1001101, 1101111, 1110010, 1101110, 1101001, 1101110, 1100111]
Summary
In this post, we have learned how to convert string to binary in Python with code example by using built in function join() ,ord() ,format() and bytearray(),map(),bin() and Math module.
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:
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 .
- Conforms to RFC 3548.
- 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:
print(binascii.crc32(b"hello world")) # Or, in two pieces: crc = binascii.crc32(b"hello") crc = binascii.crc32(b" world", crc) print('crc32 = '.format(crc))
Changed in version 3.0: The result is always unsigned.
binascii. b2a_hex ( data [ , sep [ , bytes_per_sep=1 ] ] ) ¶ binascii. hexlify ( data [ , sep [ , bytes_per_sep=1 ] ] ) ¶
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.
>>> 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'
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 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.
Support for UU encoding used on Unix.
Support for quoted-printable encoding used in MIME email messages.
Python | Convert String to Binary
Data conversion have always been widely used utility and one among them can be conversion of a string to it’s binary equivalent. Let’s discuss certain ways in which this can be done.
Method #1 : Using join() + ord() + format() The combination of above functions can be used to perform this particular task. The ord function converts the character to it’s ASCII equivalent, format converts this to binary number and join is used to join each converted character to form a string.
Python3
The original string is : GeeksforGeeks The string after binary conversion : 01000111011001010110010101101011011100110110011001101111011100100100011101100101011001010110101101110011
Time Complexity: O(N) where N is the lenght of the input string.
Auxiliary Space: O(N)
Method #2 : Using join() + bytearray() + format() This method is almost similar to the above function. The difference here is that rather than converting the character to it’s ASCII using ord function, the conversion at once of string is done by bytearray function.
Python3
The original string is : GeeksforGeeks The string after binary conversion : 01000111011001010110010101101011011100110110011001101111011100100100011101100101011001010110101101110011
Method #3 : Using join() + bin() + zfill()
we define a function str_to_binary(string) that takes in a string as its input.
We then create an empty list called binary_list, which will be used to store the binary conversions of each character in the input string.
We then use a for loop to iterate through each character in the input string. For each character, we use the ord() function to convert it to its ASCII equivalent, and then use the bin() function to convert that integer to a binary string. The bin() function returns a string with a ‘0b’ prefix, so we use list slicing to remove that prefix.
After that we use the zfill(8) method to pad the binary conversion with leading zeroes until it reaches a length of 8. The zfill() method pads the string on the left with a specified character (in this case, ‘0’) until it reaches the desired length.
Then we append the binary conversion to the binary_list and after that we join all the binary values in the list and return as a single string by using join() method.
Finally, we test the function with an example input of the string “GeeksforGeeks”. The function returns the binary string representation of the input string.