# Python bin() function

Updated on Jan 07, 2020

The bin() function returns the binary representation of the integer as a string.

Its syntax is as follows:

bin(number) -> binary representation

Parameter Description
number Any numeric value

Here is an example:

  1 2 3 4 5 6 7 8 9 10 11 12 >>> >>> bin(4) # convert decimal to binary '0b100' >>> >>> >>> bin(0xff) # convert hexadecimal to binary, 0xff is same decimal 255 '0b11111111' >>> >>> >>> bin(0o24) # convert octacl to binary, 0o24 is same decimal 20 '0b10100' >>> 
print(bin(4))
print(bin(0xff))
print(bin(0o24))


## bin() with User-defined object #

To use bin() with user-defined objects, we have to first overload the __index__() method. The __index__() method is used to coerce an object to an integer, in the context of slicing and index. For instance, consider the following:

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 >>> >>> l = [1, 2, 3, 4, 5] >>> >>> x, y = 1, 3 >>> >>> >>> l[x] 2 >>> >>> >>> l[y] 4 >>> >>> >>> l[x:y] [2, 3] >>> 
l = [1, 2, 3, 4, 5]
x, y = 1, 3
print(l[x])
print(l[y])
print(l[x:y])


When we access items in a list using indexing and slicing, internally Python calls __index__()  method of the int object.

  1 2 3 4 5 6 7 8 9 10 11 12 >>> >>> l[x.__index__()] # same as l[x] 2 >>> >>> >>> l[y.__index__()] # same as l[y] 4 >>> >>> >>> l[x.__index__():y.__index__()] # # same as l[x:y] [2, 3] >>> 
l = [1, 2, 3, 4, 5]
x, y = 1, 3
print(l[x.__index__()])
print(l[y.__index__()])
print(l[x.__index__():y.__index__()])


In addition to bin(), the __index__() method is also called when you call hex(), and oct()  on the object. Here is an example:

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 >>> >>> class Num: ... def __index__(self): ... return 4 ... >>> >>> l = [1, 2, 3, 4, 5] >>> >>> >>> n1 = Num() >>> >>> >>> bin(n1) 0b100 >>> >>> >>> hex(n1) 0x4 >>> >>> >>> oct(n1) 0o4 >>> >>> >>> l[n1] 5 >>> >>> >>> l[n1.__index__()] 5 >>> 
class Num:
def __index__(self):
return 4

l = [1, 2, 3, 4, 5]

n1 = Num()

print(bin(n1))
print(hex(n1))
print(oct(n1))
print(l[n1])
print(l[n1.__index__()])