Home > Mobile >  Convert hex to decimal/string in python
Convert hex to decimal/string in python

Time:03-20

So I wrote this small socket program to send a udp packet and receive the response

    sock.sendto(data, (MCAST_GRP, MCAST_PORT))
    msgFromServer = sock.recvfrom(1024)
    banner=msgFromServer[0]
    print(msgFromServer[0])
    #name = msgFromServer[0].decode('ascii', 'ignore')
    #print(name)

Response is

b'\xff\xff\xff\xffI\x11server banner\x00map\x00game\x00Counter-Strike: Global Offensive\x00\xda\x02\x00\x10\x00dl\x01\x011.38.2.2\x00\xa1\x87iempty,secure\x00\xda\x02\x00\x00\x00\x00\x00\x00'

Now the thing is I wanted to convert all hex value to decimal, I tried the decode; but then I endup loosing all the hex values.

How can I convert all the hex values to decimal in my case

example: \x13 = 19

EDIT: I guess better way to iterate my question is

How do I convert only the hex values to decimal in the given response

CodePudding user response:

There are two problems here:

  • handling the non-ASCII bytes
  • handling \xhh sequences which are legitimate characters in Python strings

We can address both with a mix of regular expressions and string methods.

First, decode the bytes to ASCII using the backslashreplace error handler to avoid losing the non-ASCII bytes.

>>> import re
>>>
>>> decoded = msgFromServer[0].decode('ascii', errors='backslashreplace')
>>> decoded
'\\xff\\xff\\xff\\xffI\x11server banner\x00map\x00game\x00Counter-Strike: Global Offensive\x00\\xda\x02\x00\x10\x00dl\x01\x011.38.2.2\x00\\xa1\\x87iempty,secure\x00\\xda\x02\x00\x00\x00\x00\x00\x00'

Next, use a regular expression to replace the non-ASCII '\\xhh' sequences with their numeric equivalents:

>>> temp = re.sub(r'\\x([a-fA-F0-9]{2})', lambda m: str(int(m.group(1), 16)), decoded)
>>> temp
'255255255255I\x11server banner\x00map\x00game\x00Counter-Strike: Global Offensive\x00218\x02\x00\x10\x00dl\x01\x011.38.2.2\x00161135iempty,secure\x00218\x02\x00\x00\x00\x00\x00\x00'

Finally, map \xhh escape sequences to their decimal values using str.translate:

>>> tt = str.maketrans({x: str(x) for x in range(32)})
>>> final = temp.translate(tt)
>>> final
'255255255255I17server banner0map0game0Counter-Strike: Global Offensive021820160dl111.38.2.20161135iempty,secure02182000000'

CodePudding user response:

You can first convert the bytes representation to hex using the bytes.hex method and then cast it into an integer with the appropriate base with int(x, base)

>>> b'\x13'.hex()
'13'
>>> int(b'\x13'.hex(), 16)
19

CodePudding user response:

Assume v contains the response, what you are asking for is

[int(i) for i in v]

I suspect it's not what you want, it is what I read from the question

  • Related