Как я могу изменить строку ascii на hex и наоборот в python 3.7? - PullRequest
0 голосов
/ 01 сентября 2018

Я смотрю некоторые решения на этом сайте, но те, которые не работают в Python 3.7. Итак, я задал новый вопрос.

шестнадцатеричная строка "the" is "746865"

Я хочу найти решение для преобразования "the" в "746865" и "746865" в "

Ответы [ 4 ]

0 голосов
/ 19 ноября 2018
    #!/usr/bin/python3
    """
    Program name:  ASC_to_txt.py
    The program's input is a string of hexadecimal digits.
    The string is a bytes object, and each byte is supposed to be
    the hex ASCII-code of a (capital or small) letter.

    The program's output is the string of the corresponding letters.

    Example
    Input:            746865
    First subresult:  ['7','4','6','8','6','5']
    Second subresult: ['0x74', '0x68', '0x65']
    Third subresult:  [116, 104, 101]
    Final result:     the

    References
    Contribution by alhelal to stackoverflow.com (20180901)
    Contribution by QintenG to stackoverflow.com (20170104)
    Mark Pilgrim, Dive into Python 3, section 4.6
    """
    import string

    print("The program converts a string of hex ASCII-codes")
    print("into the corresponding string of letters.")
    print("Input range is [41, 42, ..., 5a] U [61, 62, ..., 7a]. \n")
    x = input("Input the hex ASCII-codes, eg. 746865: ")

    result_1 = []
    for i in range(0,len(x)//2):
        for j in range(0,2):
            result_1.extend(x[2*i+j])
            # First subresult

    lenres_1 = len(result_1)

    result_2 = []
    for i in range(0,len(result_1) - 1,2):
        temp = ""
        temp = temp + "0x" + result_1[i]      #0, 2, 4
        temp = temp +        result_1[i + 1]  #1, 3, 5
        result_2.append(temp)
        # Second subresult

    result_3 = []
    for i in range(0,len(result_2)):
        result_3.append(int(result_2[i],16))
        # Third subresult

    by = bytes(result_3)
    result_4 = by.decode('utf-8')
    # Final result

    print("Corresponding string of letters:" + " "*6, result_4, end = "\n")
0 голосов
/ 01 сентября 2018

Если у вас есть строка байтов, то:

>>> import binascii
>>> binascii.hexlify(b'the')
b'746865'

Если у вас есть строка Unicode, вы можете закодировать ее:

>>> s = 'the'
>>> binascii.hexlify(s)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: a bytes-like object is required, not 'str'
>>> binascii.hexlify(s.encode())
b'746865'

В результате получается строка байтов, которую вы можете декодировать, чтобы получить строку Unicode:

>>> binascii.hexlify(s.encode()).decode()
'746865'

Обратное, конечно, это:

>>> binascii.unhexlify(b'746865')
b'the'
0 голосов
/ 19 ноября 2018
    #!/usr/bin/python3
    """
    Program name:  txt_to_ASC.py

    The program transfers
    a string of letters -> the corresponding
      string of hexadecimal ASCII-codes,
    eg.  the -> 746865

    Only letters in [abc...xyzABC...XYZ] should be input.

    """
    print("Transfer letters to hex ASCII-codes")
    print("Input range is [abc...xyzABC...XYZ].")
    print()
    string = input("Input set of letters, eg. the: ")
    print("hex ASCII-code: " + " "*15, end = "")

    def str_to_hasc(x):
        global glo

        byt = bytes(x, 'utf-8')
        bythex = byt.hex()

        for b1 in bythex:
            y = print(b1, end = "")
            glo = str(y)
        return glo

    str_to_hasc(string)
0 голосов
/ 01 сентября 2018

Учитывая, что ваша строка содержит только ascii (каждый символ находится в диапазоне 0-0xff), вы можете использовать следующий фрагмент:

In [28]: s = '746865'

In [29]: import math

In [30]: int(s, base=16).to_bytes(math.ceil(len(s) / 2), byteorder='big').decode('ascii')
Out[30]: 'the'

Сначала необходимо преобразовать строку в целое число с основанием 16, затем преобразовать ее в байты (при условии, что 2 байта на байт), а затем преобразовать байты обратно в строку, используя decode

...