Bin method in python

Python bin Method in Simple Words with Example

Python bin Method

Python programming language has tons of built-in functions and one of them is the bin() method.

This tutorial will give you the in-depths of the Python bin() method with examples. It will guide you through the function and application of the bin() method.

What is a bin in Python?

A bin is a method in Python and serves as an abbreviation of the word “binary“. This method takes an integer and returns its binary value in string format.

In short, the bin() method converts an integer into its binary equivalents (decimal, hexadecimal, or octal).

However, if an input is not an integer, the programmer will need to implement the _index_() method to obtain an integer value, or else, the program will raise the “TypeError” exception.

Читайте также:  background

Python bin()

To understand how the Python bin() method works, let’s take a look at the following:

Example Program

integer = 5 a = bin(integer) print('The binary equivalent of 5 is', a) 

This example program shows the basic function of bin() where it returns the binary equivalent of integer 5.

The binary equivalent of 5 is 0b101

Python bin() syntax is used in programs to invoke the bin() method.

The bin() method only takes an integer (number) as the function’s parameter. Unless the _index_() method is used, the program throws the “ValueError” exception for anything other than integers.

Return Value

This bin() method returns the binary equivalent of an integer.

For other types of objects such as strings, the method will return an error exception.

bin() in Python example program

In this section, we will try using the bin() method with an integer. Then we will discuss how each line of code process the program as a whole afterward.

Example Program

integer = 14 a = bin(integer) print('The binary equivalent of 14 is', a) 
The binary equivalent of 14 is 0b1110

Program Explanation

The first line integer = 14 is the declaration of the integer 14.

To return the corresponding binary equivalent of the integer, we apply the bin() method through a = bin(integer) . The a here is the variable containing the equivalent binary value of the integer.

The print() function then enables the program to display the value of a (the binary equivalent of 14) which is 1110 . The output includes the prefix 0b to indicate that the output is a binary value.

bin() example program with a non-integer class

In the next example, the program will show how to apply the Python bin() to non-integer classes or objects.

Example Program

class Quantity: a = 5 b = 5 c = 5 def func(): return a + b + c print('The binary equivalent of quantity is:', bin(Quantity()))
Traceback (most recent call last): File "main.py", line 9, in print('The binary equivalent of quantity is:', bin(Quantity())) TypeError: 'Quantity' object cannot be interpreted as an integer

Program Explanation

In this example, the quantity class holds the value of variables a, b, and c. To combine the quantity of the three variables, we use the def func(): and will return the sum of quantity through return a + b + c .

However, the Python bin() method only operates for integer values and as for the example given, the output raised the TypError explaining that the ‘Quantity’ object cannot be interpreted as an integer .

This example supports the fact that the bin() method does not take non-integer values, only integers or numbers.

In contrast to this situation, programmers should implement the _index_() method to enable the bin() method for non-integer values.

bin() with __index__() for Non-Integer Class

Now, let us have an example program where we apply the Python bin() method in a non-integer class but also apply the _index_() function.

Example Program

class Quantity: a = 5 b = 5 c = 5 def __index__(x): return x.a + x.b + x.c print('The binary equivalent of quantity is:', bin(Quantity()))
The binary equivalent of quantity is: 0b1111

Program Explanation

Noticeably, this example program is identical to the example above except that we apply the _index_() function. The _index_() function enables the program to identify the quantity values of variables a, b, and c through x.

The program also includes adding all of the quantity values before displaying its equivalent binary value in the output.

Therefore, the equivalent binary representation of 15 ( 5 + 5 + 5 ) is 1111 .

Using Python bin() with float

Another useful example below will help you with understanding how the Python bin() method works with float objects or decimals.

Example Program

sample_float = 12.14 print(bin(sample_float))
Traceback (most recent call last): File "main.py", line 2, in print(bin(sample_float)) TypeError: 'float' object cannot be interpreted as an integer

Program Explanation

The simple example tries to apply the bin() method with a float or decimal values.

However, the output clarifies that Python bin() does not take float values. This statement is concluded based on the Typeerror messages which say “ ‘float’ object cannot be interpreted as an integer “.

Summary

In summary, this tutorial covers the topics and discussions to explain what is a Python bin(0 method. This also clarifies how the method works with different kinds of objects or inputs that programmers may use and encounter.

Therefore, the Python bin() method is useful for returning the binary representation of any integer.

Take note that this method is only working for integer values and strings with the _index_() function.

The bottom line is the bin method is only for integers and or numbers.

Leave a Comment Cancel reply

You must be logged in to post a comment.

Источник

bin() method in python:

https://artificialintelligencestechnology.com/

bin(x) method in python convert an integer number to a binary string prefixed with “0b”. If x is not a Python int object, it has to define an __index__() method that returns an integer.

syntax:

bin() method in python Examples:

intVal=55 Binary_Number=bin(intVal) print(Binary_Number) #0b110111 Binary_Number=bin(25) print(Binary_Number) #0b11001

Convert negative numbers to binary:

bin() method can also convert negative number to binary representation.

Binary_Number=bin(-5) print(Binary_Number) #-0b101

Remove ‘0b’ from binary representation:

If you don’t want to show the prefix 0b the use the format() method.

Binary_Number=bin(25) Result=Binary_Number[2:] print(Result) #11001

Return type of bin() method:

bin() method always returns a string i.e. binary string. We can check the data type of any object using the type() method.

Binary_Number=bin(25) Result=type(Binary_Number) print(Result) #

Convert integer to binary without using bin() method:

Yes, we can use recursion to convert any decimal number to binary.

def decToBin(n): if n > 1: decToBin(n // 2) print(n % 2, end="") decToBin(2) #10

bin() method with other format integers:

bin() method not takes only integers it also can take other formats like decimal, hexadecimal, octal etc.

# Integer 15 represented in decimal decimal = 15 # Integer 15 represented in hexadecimal hexadecimal = 0xf # Integer 15 represented in octal octal = 0o17 print("Binary representation(decimal)", bin(decimal)) print("Binary representation(hexadecimal to binary)", bin(hexadecimal)) print("Binary representation(octal to binary)", bin(octal))

Non-compatible object:

If we try to pass non integer objects then an error will be raised. In the following example, we are passing float and string to the bin().

result=bin(3.14) result=bin("John")

Implement the __index__() method:

If the parameter is not an int then the object have to implement __index__() method to be converted into binary. Look at the following example.

class Total: a = 5 b = 4 def __index__(self): return self.a + self.b x = Total() # object of class Total print('The sum in binary format is', bin(x))

Источник

Python bin()

The bin() method converts a specified integer number to its binary representation and returns it.

Example

number = 15 
# convert 15 to its binary equivalent print('The binary equivalent of 15 is', bin(number))
# Output: The binary equivalent of 15 is 0b1111

bin() Syntax

The syntax of bin() method is:

bin() Parameter

The bin() method takes in a single parameter:

bin() Return Value

  • the binary string equivalent to the given integer
  • TypeError for a non-integer argument

Example 1: Python bin()

number = 5 
# convert 5 to its binary equivalent print('The binary equivalent of 5 is:', bin(number))
The binary equivalent of 5 is: 0b101

In the above example, we have used the bin() method to convert the argument 5 to its binary representation i.e. 101 .

Here, the prefix 0b in the output 0b101 represents that the result is a binary string.

Example 2: Python bin() with a Non-Integer Class

class Quantity: apple = 1 orange = 2 grapes = 2 def func(): return apple + orange + grapes print('The binary equivalent of quantity is:', bin(Quantity()))
TypeError: 'Quantity' object cannot be interpreted as an integer

Here, we have passed an object of class Quantity to the bin() method and got a TypeError.

This is because we have used a non-integer class.

Note: We can fix the TypeError above by using the Python __index__() method with a non-integer class.

Example 3: bin() with __index__() for Non-Integer Class

class Quantity: apple = 1 orange = 2 grapes = 2 def __index__(self): return self.apple + self.orange + self.grapes print('The binary equivalent of quantity is:', bin(Quantity()))
The binary equivalent of quantity is: 0b101

Here, we have passed an object of class Quantity to the bin() method.

The bin() method doesn’t raise a TypeError even if the object Quantity() is not an integer.

This is because we have used the __index__() method which returns an integer (in this case, sum of the fruits).

Recommended Readings:

Источник

Оцените статью