Python bin() function takes an integer as an argument and returns its binary representation as a string.
This function is commonly used when you need to work with binary data or perform bitwise operations.
Syntax
bin(number)
Parameters
number(required): It is an integer.
Return value
It returns a string that starts with the prefix ‘0b’.
If you try to pass a non-integer type, like a float, it will raise in a TypeError.
Example 1: Basic Usage
print("Binary of 14 is:", bin(14))
print("Binary of -14 is:", bin(-14))
Output
Binary of 14 is: 0b1110
Binary of -14 is: -0b1110
If you don’t want that prefixed 0b, you can use the format() function.
print(format(14, 'b'))
print(format(-14, 'b'))
Output
1110
-1110
Example 2: Using with a Custom Function
def custom_multiply(a, b):
return a * b
# Example usage
num1 = 4
num2 = 5
# Using the custom multiplication function
result = custom_multiply(num1, num2)
# Converting the result to binary
binary_result = bin(result)
print("Multiplication Result:", result)
print("Binary Representation:", binary_result)
Output
Multiplication Result: 20
Binary Representation: 0b10100
Example 3: Using with a Non-Integer Class
class NonIntegerClass:
def __init__(self, value):
self.value = value
# Create an instance of NonIntegerClass
non_integer_instance = NonIntegerClass("Hello")
# Trying to use bin() on an instance of NonIntegerClass will raise a TypeError
try:
print(bin(non_integer_instance))
except TypeError as e:
print(f"A TypeError was raised: {e}")
Output
A TypeError was raised: 'NonIntegerClass' object cannot be interpreted as an integer