bin() in Python
Python bin() function returns the binary string of a given integer.
Syntax: bin(a)
Parameters : a : an integer to convert
Return Value : A binary string of an integer or int object.
Exceptions : Raises TypeError when a float value is sent in arguments.
Python bin() Example
Example 1: Convert integer to binary with bin() methods
Python3
# Python code to demonstrate working of # bin() # declare variable num = 100 # print binary number print ( bin (num)) |
Output:
0b1100100
Example 2: Convert integer to binary with user define function
Python3
# Python code to demonstrate working of # bin() # function returning binary string def Binary(n): s = bin (n) # removing "0b" prefix s1 = s[ 2 :] return s1 print ( "The binary representation of 100 (using bin()) is : " , end = "") print (Binary( 100 )) |
Output:
The binary representation of 100 (using bin()) is : 1100100
Example 3: user-defined object to binary using bin() and __index()__
Here we send the object of the class to the bin methods, and we are using python special methods __index()__ method which always returns positive integer, and it can not be a rising error if the value is not an integer.
Python3
# Python code to demonstrate working of # bin() class number: num = 100 def __index__( self ): return ( self .num) print ( bin (number())) |
Output:
0b1100100
This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Please Login to comment...