基本转换方法或模块 [英] Base conversion method or module

查看:47
本文介绍了基本转换方法或模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可以在数字基础之间转换的Python模块或方法?具体来说,我需要在Hex,Decimal和Binary之间转换
,例如5Ah = 90d = 01011010b。


我在很多地方搜索但是找不到特定于Python的。


谢谢,杰夫

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

推荐答案



Jeff Wagner在消息中写道< 0b ******************************** @ 4ax.com> ...

Jeff Wagner wrote in message <0b********************************@4ax.com>...
是否有可以在数字基础之间转换的Python模块或方法?
具体来说,我需要在Hex,Decimal和Binary之间进行转换,例如5Ah = 90d = 01011010b。

我搜索了很多地方但却找不到特定于Python的地方。

谢谢,杰夫
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




有一个Python菜谱配方做了这些转换,

IIRC。浏览一下 http://aspn.activestate.com/ASPN/Cookbook/Python

数字也可以做这类事情,但我不知道。


Python本身可以让你走得很远;问题在于,使转换成为可传播的有点不稳定。


例如,int()和long()都接受一个字符串一个基本参数,所以

你可以将任何基数(2< = base< = 36)转换为Python int或

long。


Python也可以反过来,取一个数字并转换为你想要的基数的

字符串表示。问题?对于hex和oct只有一个

函数,而不是bin或任何其他基础

int可以处理。


理想情况下,有一个do-it-all函数是int()的反函数:取

a数并在任何基数中吐出一个字符串表示形式(2 -36)你想要的。


但二元情况非常简单:


def bin(数字):

""" bin(number) - > string


返回整数或长整数的二进制表示。


"""

如果数字== 0:返回''0b0''

binrep = []

而数字> 0:

binrep.append(数字& 1)

数字>> = 1

binrep.reverse()

返回''0b''+''' '.join(map(str,binrep))

处理负的int是读者的练习....


还记得Python有十六进制和八进制文字。

-

弗朗西斯阿维拉



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(number) -> string

Return the binary representation of an integer or long integer.

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

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


2003年12月7日星期日15:45:41 -0500,Francis Avila < FR *********** @ yahoo.com> wrotf:
On Sun, 7 Dec 2003 15:45:41 -0500, "Francis Avila" <fr***********@yahoo.com> wrotf:

Jeff Wagner在留言中写道< 0b ************************ ******** @ 4ax.com> ...

Jeff Wagner wrote in message <0b********************************@4ax.com>...
是否有可以在数字基础之间转换的Python模块或方法?
Is there a Python module or method that can convert between numeric bases?


具体来说,我需要to


Specifically, I need to

在Hex,Decimal和Binary之间转换,例如5Ah = 90d = 01011010b。

我在很多地方搜索但是找不到特定于Python的地方。
谢谢,杰夫
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



有一个Python菜谱配方做了这些转换,
IIRC。浏览一下 http://aspn.activestate.com/ASPN/Cookbook/Python
数字也可以做这种事情,但我不知道。

Python本身可以让你走得很远;问题在于,在使转换成为可传播方面有点不稳定。

例如,int()和long()都接受带有基本参数的字符串,所以
你可以将任何基数(2< = base< = 36)转换为Python int或
long。

Python也可以反过来,取一个数字并转换为您想要的基础的字符串表示。问题?对于hex和oct,只有一个
函数可以执行此操作,而不是bin或任何其他基础
int可以处理。

理想情况下,有是一个do-it-all函数,它是int()的反函数:取一个数字并在你想要的任何基数(2-36)中吐出一个字符串表示。

但是二元情况非常简单:

def bin(数字):
""" bin(number) - > string

返回整数或长整数的二进制表示。

"""
如果number == 0:return''0b0''
binrep = []
while number> 0:
binrep.append(number& 1)
number>> = 1
binrep.reverse()
返回''0b''+''''。join(map(str,binrep))

处理否定的int是读者的练习....
请记住,Python有十六进制和八进制文字。



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(number) -> string

Return the binary representation of an integer or long integer.

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

Remember also that Python has hex and octal literals.




弗朗西斯,


我找到了Python食谱你指的食谱。它如下:


模块名称是BaseConvert.py .......


#!/ usr / bin / env python


BASE2 =" 01"

BASE10 =" 0123456789"

BASE16 =" 0123456789ABCDEF"

BASE62 =" ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklm nopqrstuvwxyz"

def convert(number,fromdigits,todigits):


if str(数字)[0] =='' - '':

number = str(数字)[1:]

neg = 1

否则:

neg = 0

#从数字中取出一个整数

x = long(0)
str(数字)中的数字为


x = x * len(fromdigits)+ fromdigits.index(数字)


#创建结果在base''len(todigits)''

res =""

而x> 0:

digit = x%len (todigits)

res = todigits [数字] + res

x / = len(todigits)

if neg:

res =" - " + re s


返回res


导入此模块并调用它时出错。


#!/ usr / bin / python

导入BaseConvert

打印BaseConvert.convert(90,BASE10,BASE2)


名称错误:名称''Base10''未定义。


这可能与命名空间有关,这些命名空间刚刚咬我。我认为

因为''Base''定义是全局的这个模块(BaseConvert.py)通过在外面定义

函数(转换),当我导入这个模块,它们也是全球性的。


从我的一本书中,它说,导入语句创建一个包含所有
$的新命名空间b $ b模块的属性。要访问此命名空间中的属性,请使用模块的名称

object作为前缀:import MyModule ... a = MyModule.f()"这就是我以为我在做什么

做什么。


我还缺少什么?


谢谢,

Jeff



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 = "0123456789ABCDEF"
BASE62 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklm nopqrstuvwxyz"

def convert(number,fromdigits,todigits):

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(fromdigits) + fromdigits.index(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.convert(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


Jeff Wagner写道:
Jeff Wagner wrote:
我找到了你所指的Python菜谱配方。它如下:


(仅发布一个URL有什么问题?)

导入此模块并调用时出错它。

#!/ usr / bin / python
导入BaseConvert
打印BaseConvert.convert(90,BASE10,BASE2)

>名称错误:名称''Base10''未定义。

这可能与命名空间有关,这些命名空间刚刚咬我。我认为,因为''Base''定义对于这个
模块(BaseConvert.py)是全局定义的,所以在函数外部定义(转换),
当我导入这个模块时,它们将是全局的也是。 Python中的


,全局表示属于某个模块,而不是在我的整个程序中所有

模块中都可见

我还缺少什么?
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.convert(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?



更改调用以使用BaseConvert.BASE10和BaseConvert.BASE2

了解有关本地和全球名称的更多信息,请阅读:

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


< / F>




change the call to use BaseConvert.BASE10 and BaseConvert.BASE2

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

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

</F>



这篇关于基本转换方法或模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆