Ismail
Ismail

Reputation: 31

Incrementing hexa strings in 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.

Upvotes: 3

Views: 2380

Answers (2)

iabdalkader
iabdalkader

Reputation: 17332

In [15]: '{:X}'.format(int('84B8042100FE', 16)+1)
Out[15]: '84B8042100FF'

Upvotes: 2

Jon Clements
Jon Clements

Reputation: 142226

>>> 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'

Upvotes: 4

Related Questions