In this python built-in functions tutorial, we are going to learn all about the Python bin function to get the binary value of a specified integer.
In the previous python tutorial, we have seen Python any function along with examples.
Headings of Contents
What is Python bin() Function?
Python bin function is a built-in function that is used to find the binary value of a specified integer. The result of the bin function in python will always start with the prefix 0b.
Syntax
The syntax of the bin function in python is:-
bin(n)
Parameters
bin function in Python accepts only one parameter which is an integer.
- n:– Required An Integer.
Return Value
The return value of the bin function in python is a binary value. The output will always start with 0b.
Python bin function example
Here we will use the bin method in Python to get the binary version of a given integer.
Example 1: Convert integer to binary using Python bin function
Find the binary value of 20 using the bin function.
x = 20
print(bin(x))
Output will be:- 0b10100
Example 2: Convert integer to binary using a user-defined function
The binary value of 50.
def int_to_bin(num):
if type(num) == int:
return bin(num)
else:
return "You entered wrong number to convert binary."
# convert 100 to bin
print(int_to_bin(100))
# try to convert string to bin
print(int_to_bin("ProgrammingFunda"))
Output
0b1100100
You entered wrong number to convert binary.
Example 3: User-defined object to binary using bin() and index method
Here, we will convert the user-defined objects to binary using the bin() method and __index__() special method. The __index__() method will always return a positive integer and it can not be raised exception if the number is not an integer.
class intToBin:
# constructor
def __init__(self, num):
self.num = num
# method to return binary value
def __index__(self):
return (self.num)
# pass int to class
obj1 = intToBin(12)
print(bin(obj1))
Output
Binary value is:-
0b1100
Conclusion
In this tutorial, you have learned the bin method in python to find the binary value of a given integer. This is the best python built-in function for getting binary values.
If this article helped you, please keep visiting for further python built-in functions tutorials.
For more information:- Click Here