pythonsocketshexasciipyshark

How to convert python HEX ouput to ASCII?


I'd like to convert HEX output in python to ASCII when i'm using LiveCapture from pyshark.

My code:

capture = pyshark.LiveCapture(interface='en1',
                              bpf_filter='tcp port 5555 and len > 66',)

colored.OK("Interface bindée sur %s" % socket.gethostbyname(socket.gethostname()))

for packet in capture.sniff_continuously():
   if packet.ip.src == socket.gethostbyname(socket.gethostname()):
            colored.OK("Send packets")
   else:
            colored.OK("Receive packets")
            print(''.join(packet.data.data.split(":")))
            print("")

Output for receive packets:

66787874798582124495051

I'd like to convert this output to ASCII char directly in the python output Is it possible?

Thanks


Solution

  • Yes, you can convert it directly.

    def convert_HEX_to_ASCII(h):
    chars_in_reverse = []
    while h != 0x0:
        chars_in_reverse.append(chr(h & 0xFF))
        h = h >> 8
    
    chars_in_reverse.reverse()
    return ''.join(chars_in_reverse)
    
    print (convert_HEX_to_ASCII(0x6176656e67657273))
    print (convert_HEX_to_ASCII(0x636f6e766572745f4845585f746f5f4153434949))
    

    Refer link, which convert HEX to ASCII online. https://www.rapidtables.com/convert/number/ascii-to-hex.html You can verify the output manually and confirm the result.

    Similar code is available on : https://www.geeksforgeeks.org/convert-hexadecimal-value-string-ascii-value-string/