What is the Python bin() function?
bin() is an in-built function in Python that takes in integer x and returns the binary representation of x in a string format. If x is not an integer, then the _index()_ method needs to be implemented to obtain an integer as the return value instead of as a “TypeError” exception.
Code
The code below details how to convert the integer to binary using bin():
# Integer 15 represented in decimaldecimal = 15# Integer 15 represented in hexadecimalhexadecimal = 0xf# Integer 15 represented in octaloctal = 0o17print("Binary representation", bin(decimal))print("Binary representation", bin(hexadecimal))print("Binary representation", bin(octal))
Code
The code below details how to convert the user-defined object to binary using bin() and __index()__:
class Total:def __init__(self, price, quantity):self.price = priceself.quantity = quantity# Implement __index()__ to return an integerdef __index__(self):return self.price * self.quantity# supply integral values to the constructor onlytotal_price = Total(1, 4)print("Binary representation", bin(total_price))
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved