如何做十六进制增量?

时间:2014-04-30 19:42:27

标签: python

我有以下代码,它使\\network\loc\build_ver.txt中的值增加值" 1"。目前的问题是它执行整数增量,但我想做一个十六进制增量,因为输入将是一个十六进制值。

我试过这个:

with open(r'\\network\loc\build_ver.txt','r+') as f:
    value = int(f.read())
    f.seek(0)
    f.write(str(value + 1))

3 个答案:

答案 0 :(得分:11)

int builtin有一个可选的base参数,可用于读取十六进制值。

with open(r'\\network\loc\build_ver.txt','r+') as f:
    value = int(f.read(), 16)
    f.seek(0)
    f.write(hex(value + 1))

您可以使用hex作为基数16输出,或str作为基数10输出。

>>> val = int("9a", base=16)
>>> val
154
>>> hex(val + 1)
'0x9b'
>>> str(val + 1)
'155'

还值得注意的是,您应该验证输入或在某处有try块:

>>> int("g", 16)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 16: 'g'

答案 1 :(得分:4)

Python中的Hex以字符串的形式存储。增量是在整数上完成的。所以你只需要转换为整数并返回:

>>> h = '0x3f8'        # hex string
>>> i = int(h, 16)     # convert to an integer
>>> i += 1             # increment
>>> hex(i)             # convert back to hex string
'0x3f9'

希望这能很好地解决你的问题: - )

答案 2 :(得分:1)

根据Raymond的回答,我创建了一个for loop

varhex = "0x000FFF" # starting hex value
for i in range(0, 10):      # how many times you want to increment
    i = int(varhex, 16)     # define i as the decimal equivalent of varhex
    i +=1                   # increment i by one
    print (hex(i))          # print out the incremented value, but in hex form
    varhex = hex(i)         # increment varhex by 1

当我跑步时,结果列表是:

0x1000
0x1001
0x1002
0x1003
0x1004
0x1005
0x1006
0x1007
0x1008
0x1009

要运行此代码,请访问:https://repl.it/BmG9/1