base converter

Geoffrey Gerrietts geoff at homegain.com
Thu Jun 14 15:14:46 EDT 2001


> From: Fredrik Lundh [mailto:fredrik at pythonware.com]
> 
> (why has decimal to binary conversion suddenly turned into a
> FAQ the last few months?  it wasn't this way in the old days,
> and I cannot remember ever having to output things as binary
> numbers in a real-life project...  can anyone explain?)

I didn't ask, but I ran into a similar question not too long ago. I was
looking for a relatively painless way to do the same thing urllib.quote()
does for you, except that I needed to convert a handful of "sensitive"
characters that urllib.quote() doesn't handle according to the rules I need
to use (' ' -> '%20', ',' -> '%2c', '-' -> '%2d', '.' -> '%2e').

I was looking because it seemed like hex(ord(matchObj.group(0)))[2:] was two
operations too many for what I was trying to accomplish. At the time, one of
my routes of investigation was hunting for something that would give me
-just- the string represention of the number in a hexadecimal base, rather
than an eval()-able string. I was looking mostly because it seemed like a
solved problem, and solved problems are generally represented in the
libraries somewhere. It didn't occur to me at the time how difficult it
would be to generalize the solution.

Later, I came up with "%%%x" % ord(matchObj.group(0)), which was somewhat
speedier. But in the end, it was faster in almost all cases to use
urllib.quote(), then go back and convert the leftovers one at a time using
string.replace(). I'm not sure that a tool to convert between arbitrary
bases would be generally useful, or be easy to prepare in such a way as to
be more suitable than the tools we already have. And for most common
applications, a hand-rolled version as offered in this thread would do just
fine.

I think converting string data to binary is something you need to do for
steganography, too, isn't it?

Thanks,
--G.

---
Geoff Gerrietts <geoff at homegain.com>
Software Engineer, HomeGain.com
510-655-0800 x4320




More information about the Python-list mailing list