Python program to convert ASCII to Binary
Last Updated : 17 Jan, 2025
Improve
We are having a string s="Hello" we need to convert the string to its ASCII then convert the ASCII to Binary representation so that the output becomes : 01001000 01100101 01101100 01101100 0110111. To convert an ASCII string to binary we use ord()
to get the ASCII value of each character and format()
or bin()
to represent it in binary
Using ord()
and format()
ord()
function in Python returns the Unicode code point of a given character while f
ormat()
provides a way to format values into strings.
s = "Hello"
# Using a generator expression to convert each character in the string to its binary representation
b_repr = ' '.join(format(ord(char), '08b') for char in s)
print("Binary Representation:", b_repr)
Output
Binary Representation: 01001000 01100101 01101100 01101100 01101111
Explanation:
ord(char)
gets the ASCII value of the character.format(value, '08b')
converts the value to an 8-bit binary string
Using bin()
with String Slicing
bin()
function in Python converts an integer to its binary representation as a string prefixed with '0b'
.
s = "Hello"
# Using a generator expression to convert each character in the string to its binary representation
b_repr = ' '.join(bin(ord(char))[2:].zfill(8) for char in s)
print("Binary Representation:", b_repr)
Output
Binary Representation: 01001000 01100101 01101100 01101100 01101111
Explanation:
bin(ord(char))
converts the ASCII value to binary, but it includes a0b
prefix.[2:]
slices off the prefix, andzfill(8)
ensures the result is 8 bits.
Using List Comprehension and join()
Using list comprehension with join()
allows us to efficiently transform and combine string elements.
s = "Hello"
binary_representation = ' '.join([f"{ord(char):08b}" for char in s])
print("Binary Representation:", binary_representation)
Output
Binary Representation: 01001000 01100101 01101100 01101100 01101111
Explanation:
- list comprehension generates binary strings using
f"{value:08b}"
formatting. - Binary strings are joined with spaces.