Python convert number to binary

Python: Int to Binary (Convert Integer to Binary String)

Python Int to Binary Cover Image

You’ll learn a brief overview of this conversion and how binary strings are represented in computers. Then, you’ll learn how to use four different methods to use Python to convert int to binary. These include, the bin() function, string formatting, f-strings, the format() function, as well as naive implementation without the use of any functions.

The Quick Answer: Use the format() Function

Quick Answer - Python int to binary Convert Integer to Binary

What are Binary Strings for Integers?

The common integer system that we’re used to, the decimal system, uses a base of ten, meaning that it has ten different symbols. These symbols are the numbers from 0 through to 9, which allow us to make all combinations of numbers that we’re familiar with.

Binary strings, on the other hand, use a base of two, meaning that they only have two numbers to express different numbers. These numbers are either 0 or 1. While the binary number system has been in use in different ancient civilizations (such as Egypt and India), it is used extensively in electronics and computer system in modern times.

In the next sections, you’ll learn how to use Python to convert an integer to a binary using the bin() function.

Want to learn how to get a file’s extension in Python? This tutorial will teach you how to use the os and pathlib libraries to do just that!

Use Python bin to Convert Int to Binary

The Python bin() function is short for binary and allows us to convert an integer to a binary string, which is prefixed by ‘0b’ . In later section, you’ll learn how to convert the integer using Python without the prefix.

Let’s take a look at how we can turn a positive integer into a binary string using Python:

# Convert an integer to a binary string using Python bin() positive = 123 binary = bin(positive) print(binary) Returns: '0b1111011'

We can see that a binary string with the ‘0b’ prefix has been returned.

Let’s check the type of the statement that’s been returned, using the built-in type() function:

# Checking the type of our binary string positive = 123 binary = bin(positive) print(type(binary)) # Returns: #

We can see here that the function returned a string, as expected.

Now let’s see what happens when we pass in a negative integer and try to use Python to convert it to binary string:

# Convert an integer to a binary string using Python bin() negative = -123 binary = bin(negative) print(binary) Returns: '-0b1111011'

We can see that there’s also a ‘-‘ prefix to our string, letting us know that the number is a negative value.

Читайте также:  Mockito cannot mock this class interface java util list

In the next section, you’ll learn how to use Python string formatting to convert an int to a binary string.

Want to learn how to use the Python zip() function to iterate over two lists? This tutorial teaches you exactly what the zip() function does and shows you some creative ways to use the function.

Use Python String Formatting to Convert Int to Binary

If you’re wanting to convert a Python integer to a binary string without the ‘0b’ prefix, you can use string formatting.

Python string formatting allows us to define different format types for passing in values. In this case, we’ll pass in the format code of » , which allows us to convert an integer to binary.

Let’s see how we can pass in a few integer values, both positive and negative, and convert them to binary string using string formatting:

# Convert an integer to a binary string using Python string formatting positive = 123 negative = -123 positive_binary = ''.format(positive) negative_binary = ''.format(negative) print(f'') print(f'') # Returns: # positive_binary='1111011' # negative_binary='-1111011'

We can see here that this method returns the same strings, without the ‘0b’ prefix.

In the next section, you’ll learn Python f-strings to convert an int to a binary string.

Want to learn more about Python for-loops? Check out my in-depth tutorial that takes your from beginner to advanced for-loops user! Want to watch a video instead? Check out my YouTube tutorial here.

Use Python f-strings to Convert Int to Binary

Python f-strings allow us to make string formatting a little bit more intuitive. They also allow us to apply formatting to our strings in similar ways to traditional string formatting.

As a quick refresher on Python f-strings, they’re strings introduced in Python versions 3.6 and above, and are created by prefixing either a ‘f’ or ‘F’ to the string.

Let’s see how we can convert an integer to a binary string using Python f-strings. We’ll try this for the same positive and negative integers as above:

# Convert an integer to a binary string using Python f-strings positive = 123 negative = -123 positive_binary = f'' negative_binary = f'' print(f'') print(f'') # Returns: # positive_binary='1111011' # negative_binary='-1111011'

We can see here that the same values are returned. Python f-strings may not work in all versions of Python, but they are intuitive and easy to understand.

In the next section, you’ll learn how to use the Python format() function to convert an int to a binary string.

Want to learn more about Python f-strings? Check out my in-depth tutorial, which includes a step-by-step video to master Python f-strings!

Use Python format to Convert Int to Binary

Another way to convert a Python integer to a binary string is to use the built-in format() function. The format() function takes value and a format spec as its arguments.

Because of this, we can pass in a value (in this case, an integer) and a format spec (in this case “b”), to specify that we want to return a binary string.

Let’s see how we can accomplish this using Python:

# Convert an integer to a binary string using Python format() positive = 123 negative = -123 positive_binary = format(positive, 'b') negative_binary = format(negative, 'b') print(positive_binary) print(negative_binary) # Returns: # positive_binary='1111011' # negative_binary='-1111011'

This is also a very readable way in which we can convert Python integers to string. The function makes it clear that we’re converting a value to something else, even specifying a type.

Читайте также:  Javascript значение имя переменной

In the final section, you’ll learn how to convert an int to a binary string from scratch.

Want to learn how to calculate and use the natural logarithm in Python. Check out my tutorial here, which will teach you everything you need to know about how to calculate it in Python.

Convert an Int to Binary in Python without a Function

In this final section, you’ll learn how to convert how to create a naive method to convert a Python integer to a string. You’ll actually create a custom function that does this, but be able to understand how the conversion works.

Practically speaking, this is not something you’d really need to do, but it can be a helpful task to understand for programming interviews.

# Convert an integer to a binary string using a custom function def int_to_binary(integer): binary_string = '' while(integer > 0): digit = integer % 2 binary_string += str(digit) integer = integer // 2 binary_string = binary_string[::-1] return binary_string print(int_to_binary(123)) # Returns: # 1111011

Conclusion

In this post, you learned how to use Python to convert int to binary, meaning how to convert integer values to binary strings. You learned how to do this using a number of different methods, including using the Python bin() function, string formatting, f-strings, the format() function, and without any functions at all.

If you want to learn more about the Python bin() function, check out the official documentation here. To learn more about the Python format() function, you can find the official documentation here.

Источник

Python int to Binary | Integer to Binary Conversion

Python int to Binary

In the world of programming, the conversion of Python int to Binary is often necessary to better grasp the working and understanding of the computer. Before moving further, it is necessary to understand the basics. So, let us first perceive the meaning of these terms.

Int – It is the integer data type in python. It may be a positive or negative whole number without a decimal point. In python, the size of the int data type is unlimited.

Binary – It is a numeric system that comprises of solely two digits – 0 and 1.

In python there are several ways to convert an int to binary:

  • Traditional Method (Without Any Function)
  • Integer To Binary Using Bin() Function
  • Using Str.Format() Function
  • Integer To Binary Using F-Strings
  • Using Format()

Traditional method to Convert Python int to Binary (without any function):

Firstly, divide the number by 2 and add the remainder to a list. Then continue step 1 till the number is greater than 0. After this, reverse the list. At last, print the reversed list.

Source code to Convert Python int to Binary:

n=int (input ("Enter a number: ")) b= [] while(n>0): d=n%2 b.append(d) n=n//2 b.reverse() print("Binary Equivalent is: ") for i in b: print(i,end="")

Traditional method to Convert Python int to Binary (without any function):

Explanation:

At first, the user will enter a number, which in this case is 11.
The while loop iterates till the number becomes greater than 0.

In each iteration, the digit is divided by 2, and the remainder is appended to the list. The list is then reversed (As done traditionally to convert an integer to binary theoretically) and printed. As a result, we get the binary equivalent of the integer.

Читайте также:  Nginx php display error

Python int to Binary Using bin() function:

It is python’s built-in function. It takes integer as input and returns its binary representation in string format as output.

Syntax:

Parameters:

Note: if num is not an integer, __index()__ method should be implemented to return an integer. One may incur TypeError Exception

Example 1: Python int to Binary

num1 = 1 num2 = 7 print('The binary equivalent of 1 is:', bin(num1)) print('The binary equivalent of 7 is:', bin(num2))

Python int to Binary Using bin() function

Explanation:

Here the variable num1, num2 stores the integer value.

With the use of bin() function, a direct conversion of integer to binary occurs.

0b means that it is a binary string.

Example 2: Python int to Binary

class color: red = 1 blue = 2 green = 2 def __index__(self): return self.red + self.blue + self.green print('The binary equivalent of color is:', bin(color()))

Example 2: Python Integer To Binary

Explanation:

An object of class color is sent to the bin() method.

However, it doesn’t raise an error even though the object is not an integer.

This is because of the implementation of __index__() method which returns the sum of colors, which is an integer value. This sum is then passed to the bin() method.

Python int to Binary Using str.format() function:

It is a built-in function in python available for string formatting. To convert an integer to its binary equivalent, the string representation of type b can be used.

Syntax:

Parameters:

Example:

num = 5 binary = "".format(num) print('Binary equivalent of num is',binary)

Using str.format()

Explanation:

In this example, we have used the str.format() function for converting our integer to its binary equivalent (specified by using the type b). So, when the number 5 is passed as a parameter, the str.format() function converts it to its binary equivalent.

Python Int to binary using f-strings:

f-strings can be used in the version python 3.6 and above. In this, the string literal is prefixed with f or F.

Syntax:

Parameter:

It converts the parameters enclosed in curly braces <> into string

Example:

num = 5 b = f'' print('Binary equivalent of 5 is',b)

using f-strings:

Explanation:

fstring is an improved version for string formatting. When the value is passed, it is converted into binary (denoted by ‘b’), and this binary is then converted into string conveniently using the fstring.

Convert Python int to Binary Using format():

It is yet another inbuilt function available in python. It converts a specific value into a string as per the formatting specifications required by the user.

Syntax:

format(value[num, format_spec])

Parameters:

Example: Python int to Binary

num = 7 b = format(num, "b") print('Binary of 7 is',b)

Convert Python int to Binary format():

Explanation:

Format () is a built-in function available in python. Here, we have used it to convert the integer value to its binary representation. As a result, when we pass the value 7, it converts it to binary as per our specified format.

Conclusion: Python int to Binary

These are various to convert Integer to Binary in Python. So, when one is doing a program, one should keep in mind the program’s needs and constraints and choose the best possible fit, as it may differ based on requirement and personal preference.

However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.

Happy Pythoning!

Источник

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