Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Converting Hex to INT/CHAR

Tags:

python

hex

decode

I am having some difficulty changing a hex to an int/char (char preferably). Via the website; http://home2.paulschou.net/tools/xlate/ I enter the hex of C0A80026 into the hex box, in the DEC / CHAR box it correctly outputs the IP I expected it to contain.

This data is being pulled from an external database and I am not aware how it is being saved so all I have to work with is the hex string itself.

I have tried using the binascii.unhexlify function to see if I could decode it but I fear that I may not have a great enough understanding of hex to appreciate what I am doing.

Attemping to print just using an int() cast also has not produced the required results. I need some way to convert from that hex string (or one similar) to the original IP.

UPDATE: For anyone who comes across this in the future I modified the below answer slightly to provide an exact printout as an IP by using;

dec_output = str(int(hex_input[0:2], 16)) + "." +  str(int(hex_input[2:4], 16)) + "." + str(int(hex_input[4:6], 16)) + "." + str(int(hex_input[6:8], 16))
like image 742
Draineh Avatar asked Sep 29 '11 09:09

Draineh


3 Answers

A simple way

>>> s = 'C0A80026'
>>> map(ord, s.decode('hex'))
[192, 168, 0, 38]
>>> 

if you prefer list comprehensions

>>> [ord(c) for c in s.decode('hex')]
[192, 168, 0, 38]
>>> 
like image 124
Nick Dandoulakis Avatar answered Sep 20 '22 14:09

Nick Dandoulakis


If you want to get 4 separate numbers from this, then treat it as 4 separate numbers. You don't need binascii.

hex_input  = 'C0A80026'
dec_output = [
    int(hex_input[0:2], 16), int(hex_input[2:4], 16),
    int(hex_input[4:6], 16), int(hex_input[6:8], 16),
]
print dec_output # [192, 168, 0, 38]

This can be generalised, but I'll leave it as an exercise for you.

like image 29
Cat Plus Plus Avatar answered Sep 22 '22 14:09

Cat Plus Plus


You might also need the chr function:

chr(65) => 'A'
like image 38
JC Plessis Avatar answered Sep 19 '22 14:09

JC Plessis