[python] 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.

This question is related to python binary hex

The answer is


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

 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));

This overview can be useful for someone: bin, dec, hex in python to convert between bin, dec, hex in python.

I would do:

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

Result: '048d'


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())

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

Use python's binascii module

import binascii

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

print binascii.hexlify(binaryData)

Using no messy concatenations and padding :

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

Will give a hex representation with padding preserved


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

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.


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.


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'

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))

>>> 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'

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to binary

Difference between opening a file in binary vs text Remove 'b' character do in front of a string literal in Python 3 Save and retrieve image (binary) from SQL Server using Entity Framework 6 bad operand types for binary operator "&" java C++ - Decimal to binary converting Converting binary to decimal integer output How to convert string to binary? How to convert 'binary string' to normal string in Python3? Read and write to binary files in C? Convert to binary and keep leading zeros in Python

Examples related to hex

Transparent ARGB hex value How to convert a hex string to hex number Javascript: Unicode string to hex Converting Hexadecimal String to Decimal Integer Convert string to hex-string in C# Print a variable in hexadecimal in Python Convert ascii char[] to hexadecimal char[] in C Hex transparency in colors printf() formatting for hex Python Hexadecimal