Python conversion from binary string to hexadecimal

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Python conversion from binary string to hexadecimal



How can I perform a conversion of a binary string to the corresponding hex value in Python?



I have 0000 0100 1000 1101 and I want to get 048D I'm using Python 2.6.


0000 0100 1000 1101


048D




11 Answers
11



int given base 2 and then hex:


int


hex


>>> int('010110', 2)
22
>>> hex(int('010110', 2))
'0x16'
>>>

>>> hex(int('0000010010001101', 2))
'0x48d'



The doc of int:


int


int(x[, base]) -> integer

Convert a string or number to an integer, if possible. A floating



point
argument will be truncated towards zero (this does not include a string
representation of a floating point number!) When converting a string,
use
the optional base. It is an error to supply a base when converting a
non-string. If base is zero, the proper base is guessed based on the
string content. If the argument is outside the integer range a
long object will be returned instead.



The doc of hex:


hex


hex(number) -> string

Return the hexadecimal representation of an integer or long



integer.





This fails to preserve leading 0s.
– Ignacio Vazquez-Abrams
Jan 15 '10 at 14:58





@Ignacio, you're right, but I don't think the OP asked about that. In any case, ++ to your answer for pointing that out.
– Eli Bendersky
Jan 15 '10 at 16:14





@Eli: the OP specifically said he wanted 048d i.e. wants leading zero, DOESN'T want 0x
– John Machin
Jan 15 '10 at 20:44



048d





This may not preserve the leading zeroes, but it's much more readable than the clever hacks below.
– Dennis
Oct 30 '13 at 17:30





readable but wrong, @Dennis!
– babis21
Aug 8 at 9:32


bstr = '0000 0100 1000 1101'.replace(' ', '')
hstr = '%0*X' % ((len(bstr) + 3) // 4, int(bstr, 2))





@SO should really add per-language coloring. Here it thinks // is a C++ comment and grays out everything following. // in Python isn't a comment, but truncating integer division
– Eli Bendersky
Jan 15 '10 at 16:16





Brilliant answer. I am surprised why it's not upvoted/accepted yet.
– Andrei
Jul 23 '13 at 9:03





Can you explain how/why this works?
– Dennis
Oct 30 '13 at 17:31





@Dennis the first line is just cleaning up the binary string. The second line formats it as a hexadecimal string, padded to (len(bstr) + 3) // 4 hex digits, which is number of bits / 4 rounded up, i.e. the number of hex digits required. The last part of the second line parses the binary string to a number, because the %X format specifier is for numbers not binary strings.
– immibis
Mar 27 '14 at 7:41



(len(bstr) + 3) // 4


number of bits / 4





What is the equivalent in Python 3? Using "".format()
– Djunzu
Nov 1 '17 at 22:02



Use python's binascii module


import binascii

binFile = open('somebinaryfile.exe','rb')
binaryData = binFile.read(8)

print binascii.hexlify(binaryData)



Converting Binary into hex without ignoring leading zeros:



You could use the format() built-in function like this:


"0:0>4X".format(int("0000010010001101", 2))





This works only for 2-byte numbers, while Ignacio's answer works for any length.
– Andrei
Jul 23 '13 at 8:53





You still need to replace spaces if any.
– Andrei
Jul 23 '13 at 9:01



Using no messy concatenations and padding :


':0widthx'.format(int(temp,2)), width=4)



Will give a hex representation with padding preserved



Assuming they are grouped by 4 and separated by whitespace. This preserves the leading 0.


b = '0000 0100 1000 1101'
h = ''.join(hex(int(a, 2))[2:] for a in b.split())





you don't need list comprehension there
– SilentGhost
Jan 15 '10 at 15:00





good point. dunno why I always do that.
– Tor Valamo
Jan 15 '10 at 15:13


format(int(bits, 2), '0' + str(len(bits) / 4) + 'x')





You need to replace spaces before conversion.
– Andrei
Jul 23 '13 at 8:57




For whatever reason I have had issues with some of these answers, I've went and written a couple helper functions for myself, so if you have problems like I did, give these a try.


def bin_string_to_bin_value(input):
highest_order = len(input) - 1
result = 0
for bit in input:
result = result + int(bit) * pow(2,highest_order)
highest_order = highest_order - 1
return bin(result)

def hex_string_to_bin_string(input):
lookup = "0" : "0000", "1" : "0001", "2" : "0010", "3" : "0011", "4" : "0100", "5" : "0101", "6" : "0110", "7" : "0111", "8" : "1000", "9" : "1001", "A" : "1010", "B" : "1011", "C" : "1100", "D" : "1101", "E" : "1110", "F" : "1111"
result = ""
for byte in input:
result = result + lookup[byte]
return result
def hex_string_to_hex_value(input):
bin_string = hex_string_to_bin_string(input)
bin_value = bin_string_to_bin_value(bin_string)
return hex(int(bin_value, 2))



They seem to work well.


print hex_string_to_hex_value("FF")
print hex_string_to_hex_value("01234567")
print bin_string_to_bin_value("11010001101011")



results in:


0xff
0x1234567
0b11010001101011





Where is bin_value_to_hex_string?
– Léo Léopold Hertz 준영
Jul 10 '15 at 9:56



On python3 using the hexlify function:


import binascii
def bin2hex(str1):
bytes_str = bytes(str1, 'utf-8')
return binascii.hexlify(bytes_str)

a="abc123"
c=bin2hex(a)
c



Will give you back:


b'616263313233'



and you can get the string of it like:


c.decode('utf-8')



gives:


'616263313233'


x = int(input("press 1 for dec to oct,bin,hex n press 2 for bin to dec,hex,oct n press 3 for oct to bin,hex,dec n press 4 for hex to bin,dec,oct n"))


if x is 1:

decimal =int(input('Enter the decimal number: '))

print(bin(decimal),"in binary.")
print(oct(decimal),"in octal.")
print(hex(decimal),"in hexadecimal.")

if x is 2:

binary = input("Enter number in Binary Format: ");

decimal = int(binary, 2);
print(binary,"in Decimal =",decimal);
print(binary,"in Hexadecimal =",hex(decimal));
print(binary,"in octal =",oct(decimal));

if x is 3:

octal = input("Enter number in Octal Format: ");

decimal = int(octal, 8);
print(octal,"in Decimal =",decimal);
print(octal,"in Hexadecimal =",hex(decimal));
print(octal,"in Binary =",bin(decimal));

if x is 4:

hex = input("Enter number in hexa-decimal Format: ");

decimal = int(hex, 16);
print(hex,"in Decimal =",decimal);
print(hex,"in octal =",oct(decimal));
print(hex,"in Binary =",bin(decimal));


>>> import string
>>> s="0000 0100 1000 1101"
>>> ''.join([ "%x"%string.atoi(bin,2) for bin in s.split() ] )
'048d'
>>>



or


>>> s="0000 0100 1000 1101"
>>> hex(string.atoi(s.replace(" ",""),2))
'0x48d'





Using the string module is so 1990s ...
– John Machin
Jan 15 '10 at 20:41





so what's the problem? Its still in Python 2.6
– ghostdog74
Jan 15 '10 at 23:51





It's still in 2.X for the benefit of people who were using it in 1.X. string.atoi() is according to the 2.6 docs """Deprecated since version 2.0: Use the int() built-in function.""" and is not present in 3.X. The 2.X implementation of string.atoi() calls int(). There is no good reason for telling some newcomer that string.atoi() even exists let alone telling them to use it instead of telling them to use int().
– John Machin
Jan 16 '10 at 9:08






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard