-2

I have had problems with converting strings (like inputs) into denary, as a string is a necessary for using hexadecimal (as it can't be stored as an integer because of the characters a-f being included). Here are two attempts that don't work:

>>> hex_number = 'ff' #(255 in denary)
>>> ascii(0xhex_number)
SyntaxError: invalid hexadecimal literal
>>> ascii('0x'+hex_number)
"'0xff'"

I have also seen that you can use format() somehow, but that didn't work either.

>>> format(hex_number, '16') #This was what the demo said to do.
'ff              '

How can I get it so that hex_number (hexadecimal) is converted to denary (aka decimal), or any other n-base number systems?

1
  • 3
    int('ff', 16) Commented Oct 11, 2020 at 18:28

1 Answer 1

2

Turn the string into an int then back into a string

>>> n = int('ff', 16); n
255
>>> f'{n:d}'
'255'
Sign up to request clarification or add additional context in comments.

2 Comments

Oh. I didn't realise that you could adapt int() for n-base numerics. Does that make ascii() completely useless then?
I'm sure that ascii is useful for text (e.g. ümlaut or \xfcmlaut), but I have never personally had a need for it. For numbers, do not use ascii. Everything can be done through the "master" integer representation of a number, and convert to/from string representations on input/output.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.