如何读取带有base-N输入的文本文件,并将其转换为hex(最终为ascii)?

时间:2017-08-09 20:10:59

标签: python

我对Python非常陌生,我正在寻找帮助创建一个执行以下算法的程序。它的目的很简单,应该注意的是数据是一个流,所以我不能(或者至少,我不认为我可以)只打开文本文件并转换它使用单一功能。我正在开始学习语言和选项,但我想看看一些专家如何解决这个问题。不需要用户友好,我喜欢每一步输出的文件,所以我可以看到每一步的输出。

这是我推荐的算法:

Open file "base-n.txt"

For each line in file
  Remove carriage returns
  Write line to "Clean File" *#to create a single stream of characters#*

Open file "Clean File"
For each line in file
    Read the first x characters  *#I presume x depends on n in base n#*
    Convert the characters from base n to base 16
    Write the characters to "Output file"

Open file Output File
For each line in file
    Convert line to ASCII
    Print ASCII line
End

文件不大......通常只有几百行基本信息。例如,下面是base-5文本的示例。

0322040104130344042104140401011204310421011203430342043004010112020301130020
0301042104240401041401120410042204300432041401120400042104130421042401120430
0410043101120342041404010431013401120344042104200430040103440431040104310432
0424011203420400041004220410043003440410042004030112040104130410043101410112
0233043204100430011203440421042004030432040101120413041003430401042404210020
0430040104140134011204200421042001120344042104200433034204130413041004300112
0411043204300431042101120413034203440410042004100342011203420141011203130432
0430042204010420040004100430043004010112042304320410043001120413034203440432
0430011204200421042001120413041004030432041303420112040003420422041003430432
0430002004210424042003420424040101410112031004240421041004200112040003420422

提前感谢您的帮助。我期待在Python上取得更好的成绩,但短期内确实需要这种算法。

1 个答案:

答案 0 :(得分:0)

我发表评论建议hex()功能。以下是十进制到十六进制的示例:

while True:
    print("Enter 'x' for exit.")
    dec = input("Enter number in Decimal Format: ")
    if dec == 'x':
        break
    else:
        decimal = int(dec)
        print(decimal,"in Hexadecimal =",hex(decimal),"\n")