How To Do Number Formatting For Python – Binary Type

Python Number Formatting Binary Type
4 ways to convert a decimal to a binary type in Python

Python programming
Photo by Chris Ried on Unsplash

Having done a side mini project that involved binary formatting in one of the popular languages, Python, I encountered quite a difficulty in researching the different methods that can be used. They are all over the place! So, I have tried to compile the different ways that I have found into this one short article.

Here are some of the methods that I found myself use quite a couple of times in Python.

The simplest one would be this one for converting Integer into Binary form of String type:

>> bin(int)          # return "0bXXX"
# It will return a bunch of 0s and 1s with 0b in front

Another one would be the following. They would look similar to each other as they make use of the method format(), but in different ways of writing:

>> “{0:b}”.format(int) 
# It will return a bunch of 0s and 1s (return XXX)
>> format(int, 'b')
# It will return a bunch of 0s and 1s (return XXX)
>> format(int, "0b")
# It will return a bunch of 0s and 1s (return XXX)

Here are the examples for the methods above:

>> bin(2)                   # Output: 0b10
>> format(2, 'b') # Output: 10
>> format(2, "0b") # Output: 10
>> “{0:b}”.format(2) # Output: 10

In order to convert back to decimal, simply use this one for the simplest one:

int(x, base)
# int(x,2)


That’s all for now. I hope this article will help some people that are looking for different ways of conversion. Thank you for reading!

If you like what I write, please clap below and share it for others to read. Please share any of your own ways of binary conversion on the comment section below!

You can also follow me on my social media or my blog.

You can support me by tipping me (optional) through: Medium link

Or directly by clicking on either of these:

Ko-fi (recommended):

Get me a coffee:

Buy Me A Coffee

Comments

Popular posts from this blog

10 Best Practices for Naming REST API Endpoints

9 HTTP Methods You May Want To Know

4 Ways To Perform Python String Formatting