111111100101110111110
111111100101110111110

Reputation: 63

How can I store input as a hexadecimal number?

I've been working on a python app that can convert decimal numbers to hexadecimal numbers and then do the reverse. I'm having trouble with storing user input as a hexadecimal number. This is fairly crucial for my program's functioning because I need to ask which number they would like to convert back into decimal numbers. I just need to store it as a different data type other than a string or an integer but still need a prompt.

So far I have tried this method:

num = int(hex(input("Which Hexadecimal number would you like to convert to decimal/denary?  \n")))

But it still thinks that the hex number is actually a string.

Upvotes: 0

Views: 23363

Answers (2)

Jared Palmer
Jared Palmer

Reputation: 1

Here's the method I use when prompting for hex input.

First, just accept it as a regular input

hexValue1 = input("Input first hex value")

Then, convert it to its corresponding integer like so

hexValue1 = int(hexValue1, 16)

Now you can perform any math functions you want using the corresponding integer and if you want the result to be returned as a hex value be sure to return as so

print(hex(hexValue1))

Or whatever other way you want to return the value. It'll return a string in the typical 0xaa11 format. So you might need to further convert that to work with it.

So for example a simple program to take two hex value inputs and do an XOR of the two and return the hex result would look like this:

hex1 = input("Hex 1 ")
hex1 = int(hex1, 16)
hex2 = input("Hex 2 ")
hex2 = int(hex2, 16)
xor = hex1 ^ hex2

print(hex(xor))

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121168

hex() converts an integer number to a hex representation, a string. input() returns a string value instead.

You want to just store the value the user entered directly:

num = input("Which Hexadecimal number would you like to convert to decimal/denary?  \n"))

You could then verify that it is a hexadecimal number by trying to convert it to a decimal with int():

try:
    decimal = int(num, 16)  # interpret the input as a base-16 number, a hexadecimal.
except ValueError:
    print("You did not enter a hexadecimal number!")

Upvotes: 2

Related Questions