473,657 Members | 2,397 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Base conversion method or module

Is there a Python module or method that can convert between numeric bases? Specifically, I need to
convert between Hex, Decimal and Binary such as 5Ah = 90d = 01011010b.

I searched many places but couldn't find a Python specific one.

Thanks, Jeff
Jul 18 '05 #1
16 10080

Jeff Wagner wrote in message <0b************ *************** *****@4ax.com>. ..
Is there a Python module or method that can convert between numeric bases? Specifically, I need toconvert between Hex, Decimal and Binary such as 5Ah = 90d = 01011010b.

I searched many places but couldn't find a Python specific one.

Thanks, Jeff


There was a Python cookbook recipe that did these kinds of conversions,
IIRC. Look around at http://aspn.activestate.com/ASPN/Cookbook/Python.
Numeric might do this sort of thing, too, but I don't know.

Python itself can get you pretty far; the problem is that it's a bit spotty
in making conversions communicable.

For example, int() and long() both accept a string with a base argument, so
you can convert just about any base (2 <= base <= 36) to a Python int or
long.

Python can also go the other way around, taking a number and converting to a
string representation of the bases you want. The problem? There's only a
function to do this for hex and oct, not for bin or any of the other bases
int can handle.

Ideally, there's be a do-it-all function that is the inverse of int(): take
a number and spit out a string representation in any base (2-36) you want.

But the binary case is pretty simple:

def bin(number):
"""bin(numb er) -> string

Return the binary representation of an integer or long integer.

"""
if number == 0: return '0b0'
binrep = []
while number >0:
binrep.append(n umber&1)
number >>= 1
binrep.reverse( )
return '0b'+''.join(ma p(str,binrep))
Dealing with negative ints is an exercise for the reader....

Remember also that Python has hex and octal literals.
--
Francis Avila

Jul 18 '05 #2
On Sun, 7 Dec 2003 15:45:41 -0500, "Francis Avila" <fr***********@ yahoo.com> wrotf:

Jeff Wagner wrote in message <0b************ *************** *****@4ax.com>. ..
Is there a Python module or method that can convert between numeric bases?

Specifically , I need to
convert between Hex, Decimal and Binary such as 5Ah = 90d = 01011010b.

I searched many places but couldn't find a Python specific one.

Thanks, Jeff


There was a Python cookbook recipe that did these kinds of conversions,
IIRC. Look around at http://aspn.activestate.com/ASPN/Cookbook/Python.
Numeric might do this sort of thing, too, but I don't know.

Python itself can get you pretty far; the problem is that it's a bit spotty
in making conversions communicable.

For example, int() and long() both accept a string with a base argument, so
you can convert just about any base (2 <= base <= 36) to a Python int or
long.

Python can also go the other way around, taking a number and converting to a
string representation of the bases you want. The problem? There's only a
function to do this for hex and oct, not for bin or any of the other bases
int can handle.

Ideally, there's be a do-it-all function that is the inverse of int(): take
a number and spit out a string representation in any base (2-36) you want.

But the binary case is pretty simple:

def bin(number):
"""bin(numb er) -> string

Return the binary representation of an integer or long integer.

"""
if number == 0: return '0b0'
binrep = []
while number >0:
binrep.append(n umber&1)
number >>= 1
binrep.reverse( )
return '0b'+''.join(ma p(str,binrep))
Dealing with negative ints is an exercise for the reader....

Remember also that Python has hex and octal literals.


Francis,

I found the Python cookbook recipe you were referring to. It is as follows:

The module name is BaseConvert.py .......

#!/usr/bin/env python

BASE2 = "01"
BASE10 = "0123456789 "
BASE16 = "0123456789ABCD EF"
BASE62 = "ABCDEFGHIJKLMN OPQRSTUVWXYZ012 3456789abcdefgh ijklmnopqrstuvw xyz"

def convert(number, fromdigits,todi gits):

if str(number)[0]=='-':
number = str(number)[1:]
neg=1
else:
neg=0

# make an integer out of the number
x=long(0)
for digit in str(number):
x = x*len(fromdigit s) + fromdigits.inde x(digit)

# create the result in base 'len(todigits)'
res=""
while x>0:
digit = x % len(todigits)
res = todigits[digit] + res
x /= len(todigits)
if neg:
res = "-"+res

return res

I am getting an error when I import this module and call it.

#!/usr/bin/python

import BaseConvert
print BaseConvert.con vert(90,BASE10, BASE2)

Name Error: name 'Base10' is not defined.

This probably has something to do with namespaces which was biting me a while ago. I thought that
since the 'Base' definitions were global to this module (BaseConvert.py ) by being defined outside
the function (convert), that when I imported this module, they would be global, too.

From one of my books, it says, "An import statement creates a new namespace that contains all the
attributes of the module. To access an attribute in this namespace, use the name of the module
object as a prefix: import MyModule ... a = MyModule.f( )" which is what I thought I was
doing.

What am I still missing?

Thanks,
Jeff
Jul 18 '05 #3
Jeff Wagner wrote:
I found the Python cookbook recipe you were referring to. It is as follows:
(what's wrong with just posting an URL?)
I am getting an error when I import this module and call it.

#!/usr/bin/python

import BaseConvert
print BaseConvert.con vert(90,BASE10, BASE2)

Name Error: name 'Base10' is not defined.

This probably has something to do with namespaces which was biting me
a while ago. I thought that since the 'Base' definitions were global to this
module (BaseConvert.py ) by being defined outside the function (convert),
that when I imported this module, they would be global, too.
in Python, "global" means "belonging to a module", not "visible in all
modules in my entire program"
What am I still missing?


change the call to use BaseConvert.BAS E10 and BaseConvert.BAS E2

to learn more about local and global names, read this:

http://www.python.org/doc/current/ref/naming.html

</F>


Jul 18 '05 #4
On Mon, 8 Dec 2003 00:40:46 +0100, "Fredrik Lundh" <fr*****@python ware.com> wrotf:
Jeff Wagner wrote:
I found the Python cookbook recipe you were referring to. It is as follows:


(what's wrong with just posting an URL?)


What a great idea ;) ...
http://aspn.activestate.com/ASPN/Coo.../Recipe/111286
I am getting an error when I import this module and call it.

#!/usr/bin/python

import BaseConvert
print BaseConvert.con vert(90,BASE10, BASE2)

Name Error: name 'Base10' is not defined.

This probably has something to do with namespaces which was biting me
a while ago. I thought that since the 'Base' definitions were global to this
module (BaseConvert.py ) by being defined outside the function (convert),
that when I imported this module, they would be global, too.


in Python, "global" means "belonging to a module", not "visible in all
modules in my entire program"
What am I still missing?


change the call to use BaseConvert.BAS E10 and BaseConvert.BAS E2

to learn more about local and global names, read this:

http://www.python.org/doc/current/ref/naming.html

</F>

Thanks,
Jeff
Jul 18 '05 #5

"Jeff Wagner" <JW*****@hotmai l.com> wrote in message
news:ji******** *************** *********@4ax.c om...
On Sun, 7 Dec 2003 15:45:41 -0500, "Francis Avila" <fr***********@ yahoo.com> wrotf:

I am getting an error when I import this module and call it.

#!/usr/bin/python

import BaseConvert
print BaseConvert.con vert(90,BASE10, BASE2)

Name Error: name 'Base10' is not defined.

This probably has something to do with namespaces which was biting me a while ago. I thought that since the 'Base' definitions were global to this module (BaseConvert.py ) by being defined outside the function (convert), that when I imported this module, they would be global, too.
From one of my books, it says, "An import statement creates a new namespace that contains all the attributes of the module. To access an attribute in this namespace, use the name of the module object as a prefix: import MyModule ... a = MyModule.f( )" which is what I thought I was doing.

What am I still missing?
print BaseConvert.con vert(90, BaseConvert.BAS E10, BaseConvert.BAS E2)

John Roth
Thanks,
Jeff

Jul 18 '05 #6

Jeff Wagner wrote in message ...
On Mon, 8 Dec 2003 00:40:46 +0100, "Fredrik Lundh" <fr*****@python ware.com> wrotf:
Jeff Wagner wrote:
I found the Python cookbook recipe you were referring to. It is as
follows:
(what's wrong with just posting an URL?)


What a great idea ;) ...
http://aspn.activestate.com/ASPN/Coo.../Recipe/111286


Hey, I found another one which is the more general "inverse of int/long"
function I was pining for (and thus learning for the n-th time that one
should check the cookbook first before reinventing the wheel):

http://aspn.activestate.com/ASPN/Coo.../Recipe/222109

For some reason it's in the "Text" category, and uses the term "radix,"
which is less common than "base".

Hettinger's version (found in the discussion below) is better.

Shouldn't something like this get into the builtins, so we can get rid of
hex/oct in Python3k?
--
Francis Avila

Jul 18 '05 #7
>Subject: Re: Base conversion method or module
From: "Francis Avila" fr***********@y ahoo.com
Date: 12/7/2003 8:52 PM Central Standard Time
Message-id: <vt************ @corp.supernews .com>
Jeff Wagner wrote in message ...
On Mon, 8 Dec 2003 00:40:46 +0100, "Fredrik Lundh" <fr*****@python ware.com>wrotf:
Jeff Wagner wrote:

I found the Python cookbook recipe you were referring to. It is asfollows:
(what's wrong with just posting an URL?)


What a great idea ;) ...
http://aspn.activestate.com/ASPN/Coo.../Recipe/111286


Hey, I found another one which is the more general "inverse of int/long"
function I was pining for (and thus learning for the n-th time that one
should check the cookbook first before reinventing the wheel):

http://aspn.activestate.com/ASPN/Coo.../Recipe/222109


These are nice, but they're very slow:

For i=2**177149 - 1

224.797000051 sec for baseconvert
202.733999968 sec for dec2bin (my routine)
137.735000014 sec for radix

Compare those to the .digits function that is part of GMPY

0.59399998188 sec

That can make quite a difference when you're running through a couple million
iterations.


For some reason it's in the "Text" category, and uses the term "radix,"
which is less common than "base".

Hettinger's version (found in the discussion below) is better.

Shouldn't something like this get into the builtins, so we can get rid of
hex/oct in Python3k?
--
Francis Avila


--
Mensanator
Ace of Clubs
Jul 18 '05 #8
On Sun, 7 Dec 2003 21:52:23 -0500, "Francis Avila" <fr***********@ yahoo.com> wrotf:

Jeff Wagner wrote in message ...
On Mon, 8 Dec 2003 00:40:46 +0100, "Fredrik Lundh" <fr*****@python ware.com>

wrotf:
Jeff Wagner wrote:

I found the Python cookbook recipe you were referring to. It is asfollows:
(what's wrong with just posting an URL?)


What a great idea ;) ...
http://aspn.activestate.com/ASPN/Coo.../Recipe/111286


Hey, I found another one which is the more general "inverse of int/long"
function I was pining for (and thus learning for the n-th time that one
should check the cookbook first before reinventing the wheel):

http://aspn.activestate.com/ASPN/Coo.../Recipe/222109

For some reason it's in the "Text" category, and uses the term "radix,"
which is less common than "base".

Hettinger's version (found in the discussion below) is better.

Shouldn't something like this get into the builtins, so we can get rid of
hex/oct in Python3k?


Thanks Francis, this is excellent! I think I just made a major breakthrough. It's all starting to
come together. I'm sure something will stump me again, though (and it's going to be Classes when I
get there ;)

Jeff
Jul 18 '05 #9
On 08 Dec 2003 04:45:17 GMT, me********@aol. compost (Mensanator) wrotf:
Subject: Re: Base conversion method or module
From: "Francis Avila" fr***********@y ahoo.com
Date: 12/7/2003 8:52 PM Central Standard Time
Message-id: <vt************ @corp.supernews .com>
Jeff Wagner wrote in message ...
On Mon, 8 Dec 2003 00:40:46 +0100, "Fredrik Lundh" <fr*****@python ware.com>

wrotf:

Jeff Wagner wrote:

> I found the Python cookbook recipe you were referring to. It is as

follows:

(what's wrong with just posting an URL?)

What a great idea ;) ...
http://aspn.activestate.com/ASPN/Coo.../Recipe/111286


Hey, I found another one which is the more general "inverse of int/long"
function I was pining for (and thus learning for the n-th time that one
should check the cookbook first before reinventing the wheel):

http://aspn.activestate.com/ASPN/Coo.../Recipe/222109


These are nice, but they're very slow:

For i=2**177149 - 1

224.79700005 1 sec for baseconvert
202.73399996 8 sec for dec2bin (my routine)
137.73500001 4 sec for radix

Compare those to the .digits function that is part of GMPY

0.5939999818 8 sec

That can make quite a difference when you're running through a couple million
iterations.


So I decide to go and try out this GMPY and download the win32 binaries. It consists of two files,
gmpy.pyd and pysymbolicext.p yd ... what do I do with them, just copy them to the lib folder?

Then it says I need GMP-4.x so I get that, too. It's like nothing I've ever seen before. How can I
install that on my WinXP box?

Thanks, Jeff
Jul 18 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2798
by: Brian van den Broek | last post by:
Hi all, I guess it is more of a maths question than a programming one, but it involves use of the decimal module, so here goes: As a self-directed learning exercise I've been working on a script to convert numbers to arbitrary bases. It aims to take any of whole numbers (python ints, longs, or Decimals), rational numbers (n / m n, m whole) and floating points (the best I can do for reals), and convert them to any base between 2 and...
5
1395
by: Gord | last post by:
I was doing some conversion of this and that and for some reason it occurred to me that a form might be useful for this page of conversion explanation: http://www.eastontario.com/promo/baseConversion.htm Anyone out there interested in converting that page to a form method conversion display from base n to base10 to base m? m ---> 10 ---> n
4
1497
by: Alex Sedow | last post by:
Method invocation will consist of the following steps: 1. Member lookup (14.3) - evaluate method group set (Base.f() and Derived.f()) .Standart say: "The compile-time processing of a method invocation of the form M(A), where M is a method group and A is an optional argument-list, consists of the following steps:  The set of candidate methods for the method invocation is constructed. Starting with the set of methods associated with M,...
1
8328
by: Mark McDonald | last post by:
This question kind of follows on from Mike Spass’ posting 10/11/2004; I don’t understand why you can’t declare an implicit operator to convert a base class to a derived class. The text books say “neither the source nor the target types of a conversion can be a base type of the other, since a conversion would then already exist”. But this is not really true, whilst automatic (implicit) conversions do occur from the derived...
6
2486
by: Taran | last post by:
Hi All, I tried something with the C++ I know and some things just seem strange. consider: #include <iostream> using namespace std;
0
2821
by: emin.shopper | last post by:
I had a need recently to check if my subclasses properly implemented the desired interface and wished that I could use something like an abstract base class in python. After reading up on metaclass magic, I wrote the following module. It is mainly useful as a light weight tool to help programmers catch mistakes at definition time (e.g., forgetting to implement a method required by the given interface). This is handy when unit tests or...
3
1614
by: Filimon Roukoutakis | last post by:
Dear all, assuming that through a mechanism, for example reflexion, the Derived** is known explicitly. Would it be legal (and "moral") to do this conversion by a cast (probably reinterpret would work here)? The conversion is done for this purpose: I have an std::map<std::string, Base*>. I want to "associate" Derived* handles to the stored Base* so when Base* in the map changes (ie points another address), the Derived* handle outside of...
11
2696
by: jyck91 | last post by:
// Base Conversion // Aim: This program is to convert an inputted number // from base M into base N. Display the converted // number in base N. #include <stdio.h> #include <stdlib.h> #include <string.h> #define LENGTH 20 int temp, m, n, i, r, base10, true;
19
2226
by: jan.loucka | last post by:
Hi, We're building a mapping application and inside we're using open source dll called MapServer. This dll uses object model that has quite a few classes. In our app we however need to little bit modify come of the classes so they match our purpose better - mostly add a few methods etc. Example: Open source lib has classes Map and Layer defined. The relationship between them is one to many. We created our own versions (inherited) of Map...
0
8402
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
8829
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8734
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8508
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
5633
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4323
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2733
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1962
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1627
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.