Convert String to Binary in Python
String to binary
The strings can be defined as the array of Unicode code characters.
Binary
Binary is defined as the number system which consists two symbols 0 and 101. It is base-2 numeral system. The computers perform operations in binary.
The computer views the string in binary format and the binary number is an ASCCI value of string which is converted.
Method 1: Using ord() function
Firstly, we add the individual ASCII values of the string to a list with the use of ord() function.
The ord function helps in converting the character and gives the string's ASCII value.
Example:
# string initialization
test_str = "JavaTpoint"
# original string
print("The original string is : " + str(test_str))
# String to binary conversion
res = ''.join(format(ord(i), 'b') for i in test_str)
# result
print("The string after binary conversion : " + str(res))
Output:
The original string is : JavaTpoint
The string after binary conversion : 1001010110000111101101100001101010011100001101111110100111011101110100
Method 2: Using bytearray
The bytearray function is used for conversion of string. All characters are mapped into bin using bytearray and it returns the character's array in binary.
Example:
test_str = "JavaTpoint"
# original string
print("The original string is : " + str(test_str))
# String to binary converting
res = ''.join(format(i, 'b') for i in bytearray(test_str, encoding ='utf-8'))
# result
print("The string after binary conversion : " + str(res))
Output:
The original string is : JavaTpoint
The string after binary conversion : 1001010110000111101101100001101010011100001101111110100111011101110100
Method 3: Using map() function
By using bytearray, all character can also be mapped into Bin. The function bin() is used for converting decimal number into binary number.
Example:
st = "JavaTpoint"
# original string
print("The original string is : " + str(st))
result = ' '.join(map(bin, bytearray(st, "utf-8")))
# result
print("The string after binary conversion : " + str(result))print("The string after binary conversion : " + str(res))
Output:
The original string is : JavaTpoint
The string after binary conversion : 0b1001010 0b1100001 0b1110110 0b1100001 0b1010100 0b1110000 0b1101111 0b1101001 0b1101110 0b1110100