【问题标题】:how to convert hex values containing .txt file to decimal values如何将包含 .txt 文件的十六进制值转换为十进制值
【发布时间】:2017-08-28 10:17:46
【问题描述】:

这是我的 output.txt 文件

4f337d5000000001
4f337d5000000001
0082004600010000
0082004600010000
334f464600010000
334f464600010000
[... many values omitted ...]
334f464600010000
334f464600010000
4f33464601000100
4f33464601000100

我如何在 python 的帮助下将这些值更改为十进制并保存到一个新的 .txt 文件中..

【问题讨论】:

  • 欢迎来到 Stackoverflow。请通过发布您的代码以及您尝试解决问题的方法来展示您的努力。在此之前,请花时间浏览How to ask a good question 部分。另外阅读How to create a Minimal, Complete, and Verifiable example
  • 十六进制字符串表示数值的方式有很多种。你能告诉我们更多关于这些值最初是如何编码的吗?或者给一个转换的输入和输出的例子?
  • 在第一个字符串中 4f = 79 十进制,33 = 51, 7d = 125, 50 = 80 十进制我希望输出为 2-2 位。

标签: python python-2.7 hex decimal


【解决方案1】:

由于这些值是 16 位十六进制数字,我假设这些是您想要使用的 64 位整数。如果文件相当小,那么您可以使用read 引入整个字符串,并使用split 将其分解为单独的值:

with open("newfile.txt", 'w') as out_file, open("outfile,txt") as in_file:
    for hex in in_file.read().split():
        print(int(hex, 16), file=out_file)

应该为你做这件事。

【讨论】:

  • 没有。这是一个 Python 问题的 Python 答案。
  • 请注意,在 Python 2.7 中,您应该使用 print 语句或包含 python 3 print 函数和 from __future__ import print_function
  • 小注:阴影内置hex
  • 当然,如果它们是每行一个,则根本不需要拆分,只需遍历行...
  • 见鬼...甚至out_file.writelines('{}\n'.format(int(line, 16)) for line in in_file)...
【解决方案2】:

你可以这样做:

with open('output.txt') as f:
    new_file = open("new_file.txt", "w")
    for item in f.readlines():
        new_file.write(str(int(item, 16)) + "\n")
    new_file.close()

【讨论】:

    【解决方案3】:

    其中一个 cmets 提到了一个 shell 命令。这就是如何从 shell 命令行(本例中为 Linux bash)调用 Python 单行程序的方式。 I/O 重定向由 shell 处理。

    $ python -c  $'import sys\nfor line in sys.stdin: print(int(line,16))' <hex.txt >dec.txt
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-05
      • 2011-12-31
      • 2014-10-10
      • 2020-11-15
      • 2017-04-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多