How to use the bin() function in Python
In this post, we are going to learn how to use bin() function in Python. This method accepts an integer and will return a binary-equivalent string of the integer you had given. You can also convert a decimal value to a binary using a recursion method. You can use this python code to convert the decimal value to binary using recursion.
def func(n): if n > 1: func(n//2) print (n%2,end="") if __name__ == '__main__': func(8)
This program works fine but python offers us a better way to do this. The bin() method in python is easier to use and also reduces the lines of code (loc) as well. When you are working in a big project and often you have to convert decimal values to binary strings the bin() function is very helpful!
Syntax of bin() function in Python
n is an integer value which will be converted to its binary equivalent.
This function will return the binary-equivalent string of the given integer.
Also please note that if you pass a float value instead of an integer value, doing so will raise a TypeError Exception.
def func(n): s=bin(n) return s if __name__ == '__main__': number = 8 result = func(number) print("The Binary Equivalent of",number,"is ") print(result)
The time complexity of bin() function in python is O(log(n)).
Output for the above Code
Note – Here the prefix 0b means that the string is a binary string.