Python - Converting Hex to INT/CHAR

后端 未结 6 2142
你的背包
你的背包 2020-12-10 16:54

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 he

相关标签:
6条回答
  • 2020-12-10 17:19

    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]
    >>> 
    
    0 讨论(0)
  • 2020-12-10 17:19

    For converting hex-string to human readable string you can escape every HEX character like this:

    >>> '\x68\x65\x6c\x6c\x6f'
    'hello'
    

    from string you can easily loop to INT list:

    >>> hextoint = [ord(c) for c in '\x68\x65\x6c\x6c\x6f']
    >>> _
    [104, 101, 108, 108, 111]
    

    Your example:

    >>> [ord(c) for c in '\xC0\xA8\x00\x26']
    [192, 168, 0, 38]
    
    0 讨论(0)
  • 2020-12-10 17:31
    >>> htext='C0A80026'
    >>> [int(htext[i:i+2],16) for i in range(0,len(htext),2)]
    # [192, 168, 0, 38]
    
    0 讨论(0)
  • 2020-12-10 17:32

    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.

    0 讨论(0)
  • 2020-12-10 17:34

    You might also need the chr function:

    chr(65) => 'A'
    
    0 讨论(0)
  • 2020-12-10 17:38

    I hope it's what 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 讨论(0)
提交回复
热议问题