In this article, we will learn about python bin() function with examples.
Getting Started
bin() function in python is used to convert an integer into equivalent binary value. For example,
If we take 2 as integer and use it with bin() function, we will get 10. 10 is equivalent binary of 2.
Similarly,
For 3, it’s 11
For 4, it’s 100
and so on for other integer value.
Syntax of bin() Function
Syntax of python bin() Function –
bin(INT_VALUE)
Where,
INT_VALUE is an integer value.
Parameter of bin() Function
As discussed above,
bin() Function accepts only one argument –
- INT_VALUE: Argument passed to bin() Function must be integer value.
Return Value of bin() Function
bin() Function returns binary equivalent of passed integer as argument.
Examples of bin() Function
Now, Let’s see some examples of bin() Function in python –
Example 1: Converting an integer into binary using bin() Function
# Declare variable num = 32 # Prints binary equivalent of num print(bin(num))
Output:
0b100000
Here,
0b represents binary.
binary equivalent of 32 is 100000.
Visit to learn more ways to print integer
Please note that result includes 0b as well. So, we if want to get only binary equivalent value, we can define another function as shown below –
Example 2: Using user-defined Function with bin()
def ConvertBinary(n): num = bin(n) # Removes "0b" prefix num1 = num[2:] return num1 print("The binary representation of 32 is : ", end="") print(ConvertBinary(32))
Output:
The binary representation of 32 is : 100000
Now, we got the desired result and printed it using print() method.
Now, what if we need to use bin() function with object ?
Example 3: Using bin() Function with Class
Let’s take an example where we want to bin() function with non-integer object –
class Student: class8 = 10 class9 = 20 class10 = 2 def func(): return class8 + class9 + class10 print('Equivalent Binary of Student is:', bin(Student()))
Output:
TypeError: 'Student' object cannot be interpreted as an integer
We got this error because Student() is not an integer.
To fix this issue, we need to use __index()__ Function.
Example 4: Using bin() Function with __index()__ Function
class Student: class8 = 10 class9 = 20 class10 = 2 def __index__(self): return self.class8 + self.class9 + self.class10 print('Equivalent Binary of Student is:', bin(Student()))
Output:
Equivalent Binary of Student is: 0b100000
self.class8 + self.class9 + self.class10 is equal to 32. Binary of 32 is 100000. Hence, output is 0b100000.
Learn more at official doc.