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
The following 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 share it for others to read. Please share any of your own ways of binary conversion on the comment section if any!
Top comments (0)