Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to do a hexadecimal increment?

Tags:

python

I have the following code which increments the value in \\network\loc\build_ver.txt by value "1". The issue currently is that it does an integer increment, but I want to do a hexadecimal increment because the input is going to be a hexadecimal value.

I've tried this:

with open(r'\\network\loc\build_ver.txt','r+') as f:
    value = int(f.read())
    f.seek(0)
    f.write(str(value + 1))
like image 601
python.beginner Avatar asked Apr 30 '14 19:04

python.beginner


3 Answers

The int builtin has an optional base parameter, which you can use to read hex values.

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

You can use hex for base 16 output or str for base 10 output.

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

It's also worth noting that you should either validate the input or have a try block somewhere:

>>> int("g", 16)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 16: 'g'
like image 199
Daenyth Avatar answered Oct 22 '22 16:10

Daenyth


Hex is in Python is stored in the form of strings. Incrementing is done on integers. So you just need to convert to an integer and back:

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

Hope this solves your problem neatly :-)

like image 33
Raymond Hettinger Avatar answered Oct 22 '22 16:10

Raymond Hettinger


Based on Raymond's answer, I created a 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

and when I run, the resulting list is:

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

To run this code visit: https://repl.it/BmG9/1

like image 27
Ingrid Stevens Avatar answered Oct 22 '22 15:10

Ingrid Stevens