Python - Convert Hex to INT / CHAR

I find it difficult to change hex to int / char (char is preferred). Through the website; http://home2.paulschou.net/tools/xlate/ I enter the hexadecimal code C0A80026 in the hexadecimal field, in the DEC / CHAR field it correctly displays the IP address that I expected from it to contain.

This data is extracted from an external database, and I do not know how it is stored, so all I have to work with is the hexadecimal string itself.

I tried using the binascii.unhexlify function to see if I can decode it, but I'm afraid that I may not have enough understanding of the hex to evaluate what I'm doing.

When trying to print only using the int () method, the required results were also not obtained. I need to somehow convert from this hexadecimal string (or one like that) to the original IP address.

UPDATE: for anyone facing this in the future, I slightly modified the answer below to provide an accurate printout as IP 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)) 
+6
source share
5 answers

If you want to get 4 separate numbers from this, then treat it like 4 separate numbers. You do not 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 may be generalized, but I will leave it as an exercise for you.

+6
source

Easy way

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

if you prefer list comprehension

 >>> [ord(c) for c in s.decode('hex')] [192, 168, 0, 38] >>> 
+6
source

You may also need the chr function:

 chr(65) => 'A' 
+4
source
 >>> htext='C0A80026' >>> [int(htext[i:i+2],16) for i in range(0,len(htext),2)] # [192, 168, 0, 38] 
+1
source

I hope you expect:

 hex_val = 0x42424242 # hexadecimal value int_val = int(hex_val) # integer value str_val = str(int_val) # string representation of integer value 
0
source

Source: https://habr.com/ru/post/898267/


All Articles