TransWikia.com

Problem in executing code to convert hexadecimal to decimal

Stack Overflow Asked by user13882705 on December 5, 2021

I have this problem:

n = int(input("Enter Hexadecimal Number: ")
print(0xn)

I found that it works when n is already defined…
Also how to convert it when the number is a string like 2ABF

2 Answers

The 0b, 0o, and 0x modifiers only work with int literals, by which I mean, when you're writing the integer literally in code. You can't simply apply them to a variable that already has a value, as integers aren't stored with any particular base in mind (that only matters when you display them somehow).


When converting a string to an int, you can specify the base it's in as a second argument:

n = int("AF", 16)
# 175

For bases beyond 16, it continues to use the rest of the alphabet, up to 36, after which point it refuses to continue because there are no more letters, forcing you to write your own.


When converting an int to a string, there's no particular one-size-fits-all method. However, for the common bases in particular, there are built-in functions:

bin(n)  # '0b10101111' - base 2
oct(n)  # '0o257' - base 8
hex(n)  # '0xaf' - base 16

You can then do the usual string manipulation on these to get rid of the first two characters and make the hex all-uppercase, if you want:

print(hex(n)[2:].upper())
# AF

Answered by Green Cloak Guy on December 5, 2021

Try as follow:

n = input("Enter Hexadecimal Number: ")
print(hex(int('0x' + n, 16)))

Answered by Mateo Lara on December 5, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP