icon

Convert Character to Binary in Python

Last modified: 2023-08-29

We can convert a character to binary using the format method in Python.

Conversion

Character -> N-bit

Using format method, the given character is converted to bits.

char = 'a'
format(ord(char), 'b')
# 1100001

Character -> 8-bit

We can specify 8-bit representation by prepending {0:08b} before the format method.

char = 'a'
'{0:08b}'.format(ord(char), 'b')
# 01100001

Character -> 16-bit

We can specify 16-bit representation by prepending {0:016b} before the format method.

char = 'a'
'{0:016b}'.format(ord(char), 'b')
# 0000000001100001