-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?

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
WaeVaR
  • 56
  • 8

1 Answers1

2

Turn the string into an int then back into a string

>>> n = int('ff', 16); n
255
>>> f'{n:d}'
'255'
spagh-eddie
  • 124
  • 9
  • Oh. I didn't realise that you could adapt int() for n-base numerics. Does that make ascii() completely useless then? – WaeVaR Oct 11 '20 at 18:30
  • 1
    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. – spagh-eddie Oct 11 '20 at 18:55