[Tutor] Re: number conversion problem (was: Re: [no subject])
Gregor Lingl
glingl at aon.at
Tue Jun 8 20:43:23 EDT 2004
Dragonfirebane at aol.com schrieb:
>basically, i'm writing a program to convert text into binary into hexadecimal in all the possible combinations of those (text - bin, text - hex, bin - text, bin - hex, hex - bin, hex - text). while more mathematical possibilities no doubt exist, i'm not up to delving into 'math' right at this moment. also, i wanted to make it work without importing too many things.
>
>
>
Hi Dragonfirebane!
I see a problem in your problem statement:
You want to make the following conversions:
text - bin, text - hex, bin - text, bin - hex, hex - bin, hex - text
Incidentally, if you output a number you always oputput
a string-representation of a number, and you want to get
representations of the same number with different bases (2, 16,
*and* 10 --- what you called 'text'). In fact all those are texts. But
there is a number (behind the scenes), which is - I suppose -
stored as a binary number in the computer-memory.
The default way to output this number Python uses is in decimal format.
If you want to make conversions of the sort bin - hex you have
to convert a binary representation of some number into the number
(the value) and then this value again into a string representation
with some other base.
In fact Python has a built in function, which converts the
string-representation of a number with an arbitrary base < 36
into a number:
>>> int("ff",16)
255
>>> int("1111",2)
15
>>> int("1001",10)
1001 ;-)
The interactive Python interpreter doesn't use quotes '...' when
printing (the decimal representations of) numbers in order
to show that these are stored internally as number objects,
and knowing that we cannot think of numbers without using a
representation ... (confusing?). And moreover knowing, that
the decimal representation is the only one we are accustomed to ...
Unfortunately Python - as far as I know - does not have
the reverse function, e.g. numstr, which would work like:
>>> num2str(255,16)
'ff'
>>> num2str(15,2)
'1111'
etc.
With such a function we easily could get something like
def convert(number_representation, from_base, to_base):
number = int(number_representation, from_base)
return num2str(number, to_base)
I fear, that this 'explanation' raises more questions than
it solves- so I'll stop here. Feel free to ask more
questions on this, if you like. Certainly there are
people listening and writing to this list, who will
help to clarify those things much better than I can ....
Gregor
More information about the Tutor
mailing list