Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting hexadecimal , octal numbers into decimal form using python script

Tags:

python

hex

octal

There are many inbulit functions like int(octal) which can be used to convert octal numbers into decimal numbers on command line but these doesn't work out in script . int(0671) returns 0671 in script, where as it represent decimal form of octal number on python command line. Help???

Thank You

like image 626
Harshit Sharma Avatar asked Dec 10 '22 15:12

Harshit Sharma


1 Answers

There's some confusion here -- pedantically (and with computers it's always best to be pedantic;-), there are no "octal numbers", there are strings which are octal representations of numbers (and other strings, more commonly encountered, which are their decimal representations, hexadecimal representations). The underlying numbers (integers) are a totally distinct type from any of the representations (by default their decimal representation is shown) -- e.g.:

>>> 2 + 2
4
>>> '2' + '2'
'22'

the quotes indicate strings (i.e., representations) -- and note that, per se, they have nothing to do with the numbers they may be representing.

So, one way to interpret your question is that you want to convert an octal representation into a decimal one (etc) -- that would be:

>>> str(int('0671', 8))
'441'

note the quoted (indicating strings, i.e., representations). int(s, 8) converts the string s into an integer as an octal representation (or raises an exception if the conversion can't work). str(n) produces the string form of number n (which, as I mentioned, is by default a decimal representation).

like image 111
Alex Martelli Avatar answered Dec 12 '22 04:12

Alex Martelli