CandyGum
CandyGum

Reputation: 511

Adding/Subtracting Hexadecimals

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 :)

Upvotes: 5

Views: 32737

Answers (2)

Vickie
Vickie

Reputation: 31

Zombie! but this was the first google hit so I am adding on here.

If you can convince the user to enter in hex format (0x100) you can just do normal math.

basenum = 0x100
addnum =0x10
total = basenum + addnum

Upvotes: 0

CandyGum
CandyGum

Reputation: 511

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.

Upvotes: 17

Related Questions