Python bin() Function

Python’s built-in bin(integer) function takes one integer argument and returns a binary string with prefix "0b". If you call bin(x) on a non-integer x, it must define the __index__() method that returns an integer associated to x. Otherwise, it’ll throw a TypeError: object cannot be interpreted as an integer.

ArgumentintegerAn integer value or object implementing the __index__() method.
Return ValuestringReturns a string of binary numbers, prefixed with with "0b".
Input : bin(1)
Output : '0b1'

Input : bin(2)
Output : '0b10'

Input : bin(4)
Output : '0b100'

Input : bin(8) 
Output : '0b1000'

Input : bin(42)
Output : '0b101010'

Check out my new Python book Python One-Liners (Amazon Link).

If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!

The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).

Publisher Link: https://nostarch.com/pythononeliners

Examples bin()

The following code shows you how to use the bin() function on different input arguments.

# Integer to Binary
print(bin(8))
# 0b1000

# Integer to Binary
print(bin(16))
# 0b10000

# Integer to Binary
print(bin(129))
# 0b10000001

# Custom class to Binary
class Lst:
    def __index__(self):
        return 129

x = Lst()
print(bin(x))
# 0b10000001

# List to Binary? --> Error!
print(bin([1, 2, 3]))
# TypeError: 'list' object cannot be interpreted as an integer

You can observe multiple properties of the bin() function:

  • It’s always prefixed with '0b' for binary.
  • It returns a string representation of the integer converted to a binary.
  • If you pass an object of a class implementing the __index__ method returning an integer, bin(object) returns the binary associated to the returned value.
  • If you pass an object of a class not implementing the __index__ method, it’ll throw a TypeError: object cannot be interpreted as an integer

Python bin() Without ‘0b’ Prefix

To skip the prefix, use slicing and start with index 2 on the binary string. For example, to skip the prefix '0b' on the result of x=bin(2)='0b10', use the slicing operation x[2:] that results in just the binary number '10' without the prefix '0b'.

Here are a few examples:

>>> bin(2)
'0b10'
>>> bin(2)[2:]
'10'
>>> x = bin(42)
>>> x
'0b101010'
>>> x[2:]
'101010'

Inferior methods are based on Python’s format() function:

>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')

Python bin() Padding

Problem: How to convert an integer to a binary using the bin() function but without removing the leading zeros. For example, the result should be always 8 bit long:

bin(2) -> 0b10

# What you want:
bin(2) -> 0b00000010

How to accomplish this?

Solution: Use the format() function to define the exact format you require.

>>> format(14, '#010b')
'0b00001110'

The format() function allows you to use the Format Specification Mini Language (FSML). Let’s go from left to right over the symbols in the FSML argument.

  • Use the hashtag # to include the 0b prefix.
  • Use the 0 format character to set the padding character.
  • Use the 10 size formats the output to fit in 10 characters width. Two of those 10 characters are for the '0b' prefix, so that 8 bits remain in the binary string.
  • Use the b format character to format the result as a binary.

Summary

Python’s built-in bin(integer) function takes one integer argument and returns a binary string with prefix "0b".

If you call bin(x) on a non-integer x, it must define the __index__() method that returns an integer associated to x.

Otherwise, it’ll throw a TypeError: object cannot be interpreted as an integer.

An example is the call bin(3) which results in the binary string '0b11' because the binary number of decimal 3 is binary 11.

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!