Function signature
bin(integerNum)
Parameters
integerNum - An integer in base-10, base-16, base-8 and base-2 format. In other words any integer following decimal(not to be made ambiguity with fractions), hexadecimal, octal or binary number systems.
Return value
A binary string. A string containing 1s and 0s.
Overview
- The bin() function returns the binary representation of an integer as a string. The function takes an integer of base-10, base-16, base-8 and base-2 format as input and returns the binary string of bits - ones and zeros. A binary number follows base-2 format.
- The binary string will have a prefix '0b' denoting binary value. Note that the returned binary string is a valid Python expression which can be passed inside the function eval() to get the integer value back in base-10 format.
- For the bin() function to accept any object representing an integer value as parameter, the corresponding class should have the __index__() method defined.
- If the binary string needs to be prefixed with zeros based on a given width, function like numpy.binary_repr() can be used.
- A binary number has a base of 2. The maximum value of a digit in binary number system is 1. The minimum value is 0. A binary digit is often called a “bit”. A binary digit assumes one of the values: 0 or 1.
Exceptions
The bin() function will raise a TypeError if an invalid type e.g., a floating point value is passed as a parameter.
Example 1 - Converting an integer to binary string
# Example Python program that converts
# integers of base-10, base-16, base-8 and base-2
# into binary strings using the built-in function bin()
# Convert decimal number to binary string
num = 8
binString = bin(num)
print(binString)
# Convert hexadecimal number to binary string
num = 0xE0
binString = bin(num)
print(binString)
# Convert octal number to binary string
num = 0o370
binString = bin(num)
print(binString)
# Convert binary number to binary string
num = 0b1001
binString = bin(num)
print(binString)Output
0b1000
0b11100000
0b11111000
0b1001Example 2 - Convert a custom integer object to binary string
This Python example code below creates a custom integer class by defining class IntClass. The IntClass implements the __index__() method and returns the integer value it represents. When the built-in bin() function is called by passing an object of IntClass as parameter, the __index__() method is invoked internally by the bin() function and the returned integer value is converted to a string of binary bits - 1s and 0s.
# 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##