Function Name:
bin(number)
Function Overview:
- The bin() function returns the binary representation of an int object as a string.It takes an integer in decimal format and converts it to binary format.
- The returned value is of type string containing the binary value of the integer.
- The binary string will have a prefix '0b' denoting binary value. Remember that the returned binary string is a valid python expression which can be passed inside the function eval() to get the integer value back.
- For the bin() function to work on any other object representing an integer value the class corresponding that object has to defined with a __index__() method.
Example1:
# Define an integer value x = 10
# convert the integer to a binary string binaryString = bin(x)
print("Binary string of {} is {}".format(x, binaryString))
#convert the binary back to decimal y = eval(binaryString)
print("Binary converted back to decimal:{}".format(y)) |
Output:
Binary string of 10 is 0b1010 Binary converted back to decimal:10 |
Example2:
# class representing a numeric val class IntClass: myVal = 0
def __init__(self, aVal_in): self.myVal = aVal_in
#Has to define the __index__() method def __index__(self): return self.myVal
#Use bin() to convert an IntClass instance CustomInt = IntClass(2) CustomIntBinary = bin(CustomInt)
print("Custom integer object as binary string:{}".format(CustomIntBinary))
|
Output:
Custom integer object as binary string:0b10 |
Exceptions:
The bin() function will raise a TypeError if an invalid type like a floating point value is passed as a parameter.