Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding/Subtracting Hexadecimals

Tags:

python

How can I add/subtract hexadecimal's that the user inputs?

Like:

basehex = input()
sechex = input()

sum = hex(basehex - sechex)



print(sum)

I get: TypeError: unsupported operand type(s) for -: 'str' and 'str'

How do I do this? Must I convert them to int? Then I can't have them as hex (0xFFFFFF)...?

The only way I can do it is:

basehex = int('255')
sechex = int('255')

sum = hex(basehex - sechex)



print(sum)

But this requires me to enter basehex/sechex as numbers, since int won't take it otherwise:

ValueError: invalid literal for int() with base 10: 'ff'

Thanks :)

like image 842
CandyGum Avatar asked Dec 19 '22 05:12

CandyGum


1 Answers

Thanks to @Peri461

basehex = input()
sechex = input()

basehexin = int(basehex, 16)
sechexin = int(sechex, 16)



sum = basehexin - sechexin



print(hex(sum))

This code will do it, by converting the hexadecimals to decimals, subtracting them, then converting(representing) them to hexadecimals again.

like image 166
CandyGum Avatar answered Dec 20 '22 19:12

CandyGum