75

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.

Teun Zengerink
  • 4,277
  • 5
  • 30
  • 32
sylvain
  • 759
  • 1
  • 5
  • 3

13 Answers13

95

int given base 2 and then hex:

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

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

The doc of 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(number) -> string

Return the hexadecimal representation of an integer or long

integer.

ivan_pozdeev
  • 33,874
  • 19
  • 107
  • 152
Eli Bendersky
  • 263,248
  • 89
  • 350
  • 412
35
bstr = '0000 0100 1000 1101'.replace(' ', '')
hstr = '%0*X' % ((len(bstr) + 3) // 4, int(bstr, 2))
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • 4
    @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
  • 1
    Brilliant answer. I am surprised why it's not upvoted/accepted yet. – Andrei Jul 23 '13 at 09:03
  • 2
    @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. – user253751 Mar 27 '14 at 07:41
  • What is the equivalent in Python 3? Using "".format() – Djunzu Nov 01 '17 at 22:02
27

Use python's binascii module

import binascii

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

print binascii.hexlify(binaryData)
user3394040
  • 947
  • 13
  • 22
7

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))
Community
  • 1
  • 1
Gareth Williams
  • 623
  • 5
  • 9
4

Using no messy concatenations and padding :

'{:0{width}x}'.format(int(temp,2), width=4)

Will give a hex representation with padding preserved

Darien
  • 3,482
  • 19
  • 35
Sam Palmer
  • 1,675
  • 1
  • 25
  • 45
3

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'
babis21
  • 1,515
  • 1
  • 16
  • 29
3

I would do:

dec_str = format(int('0000010010001101', 2),'x')
dec_str.rjust(4,'0')

Result: '048d'

Tomas
  • 71
  • 5
3

To convert binary string to hexadecimal string, we don't need any external libraries. Use formatted string literals (known as f-strings). This feature was added in python 3.6 (PEP 498)

>>> bs = '0000010010001101'
>>> hexs = f'{int(bs, 2):X}'
>>> print(hexs)
>>> '48D'

If you want hexadecimal strings in small-case, use small "x" as follows

f'{int(bs, 2):x}'

Where bs inside f-string is a variable which contains binary strings assigned prior

f-strings are lost more useful and effective. They are not being used at their full potential.

neotam
  • 2,611
  • 1
  • 31
  • 53
0
format(int(bits, 2), '0' + str(len(bits) / 4) + 'x')
Dmitry Sobolev
  • 927
  • 15
  • 18
0

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())
Tor Valamo
  • 33,261
  • 11
  • 73
  • 81
0

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
onaclov2000
  • 5,741
  • 9
  • 40
  • 54
-2
>>> 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'
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
  • so what's the problem? Its still in Python 2.6 – ghostdog74 Jan 15 '10 at 23:51
  • 1
    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 09:08
-3
 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));
YogVj
  • 1