Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incrementing hexa strings in Python

Tags:

python

I'm trying in python to increment hexa decimal values that are represented in strings like '84B8042100FE', how can i increment this value with 1 to have '84B8042100FF' ?

thank you.

like image 207
Ismail Avatar asked Jan 18 '26 12:01

Ismail


2 Answers

>>> s = '84B8042100FE'
>>> num = int(s, 16) + 1
>>> hex(num)[2:].upper()
'84B8042100FF'

And the much better method I always forget about - Thanks @Martijn Pieters

>>> '{:X}'.format(num)
'84B8042100FF'
like image 65
Jon Clements Avatar answered Jan 21 '26 00:01

Jon Clements


In [15]: '{:X}'.format(int('84B8042100FE', 16)+1)
Out[15]: '84B8042100FF'
like image 21
iabdalkader Avatar answered Jan 21 '26 01:01

iabdalkader



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!