Python bin built-in function

Here we will discuss the python bin() built-in function. The python bin() built-in function is use to get the binary string digit of any integer object. The binary digit returned by the bin() function has ‘0b‘ in the front.

Note this function can accept only integer object and it will return its binary digit, if any non-integer object is passed as the argument you will get an error. If the non-integer object passed have an __index__() function which return an integer then it is fine.

>>> bin( 90 )
'0b1011010'
>>> bin( 1111 )
'0b10001010111'
>>> bin( 101010110 )
'0b110000001010100101010111110'
>>> bin( -190)
'-0b10111110'

As you can see even negative integer is acccpeted by the function.

Testing bin() with non-integer object.

>>> bin( '90' )
Traceback (most recent call last):
  File "<pyshell#140>", line 1, in <module>
    bin( '90' )
TypeError: 'str' object cannot be interpreted as an integer
>>> bin( 90.45)
Traceback (most recent call last):
  File "<pyshell#141>", line 1, in <module>
    bin( 90.45)
TypeError: 'float' object cannot be interpreted as an integer
bin( [34] )
Traceback (most recent call last):
  File "<pyshell#142>", line 1, in <module>
    bin( [34] )
TypeError: 'list' object cannot be interpreted as an integer

String ,floating-point value and list also fails.

If you wish to remove the ‘0b’ prefix you can use the format() function.

>>> format( 90 , 'b' )
'1011010'
>>> format( 1111 , 'b' )
'10001010111'

Passing non-integer object

As said earlier if a non-integer object is passed to bin() function it must have __index__() to be valid. Else the bin will return an error.

Let’s try to make a non-integer object wit hand wihtout __index__() function and see if bin() works.

>>> #Class without __index__() function
>>> class new:
	arg=90
	def funct():
		return arg

>>> #Class with __index__() function
>>> class new123:
	arg=90
	def __index__( new_obj ):
		return new_obj.arg

	
>>> bin( new() )
Traceback (most recent call last):
  File "<pyshell#194>", line 1, in <module>
    bin( new() )
TypeError: 'new' object cannot be interpreted as an integer
>>> bin( new123() )
'0b1011010' 

As you can see calling bin( new()) fails but bin( new123() ) succeds. The binary digit returned by bin( new123()) is the binary of the integer value 90.

if you want the ‘class new’ to be interpretable to the integer object then add the __index() function.




Leave a Reply

Your email address will not be published. Required fields are marked *