Python论坛  - 讨论区

标题:[python-chinese] 关于把整数转为2进制的方法。

2006年06月05日 星期一 18:25

Leo Jay python.leojay at gmail.com
Mon Jun 5 18:25:44 HKT 2006

大家好。
今天琢磨了一下怎么把一个整数转为2进制。
把我的解法共享给大家看看,抛砖引玉,看看有没有更好的解法  ;)

import math

# 把整数转为2进制。只处理非负数
def bin(num):
 if num == 0:
  return '0'
 return "".join([str((num>>i)&1) for i in xrange(int(math.floor(math.log(num,
2))),-1,-1)])

for i in xrange(20):
 print bin(i)
运行的结果是这样的:
0
1
10
11
100
101
110
111
1000
1001
1010
1011
1100
1101
1110
1111
10000
10001
10010
10011

-- 
Best Regards,
Leo Jay
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.exoweb.net/pipermail/python-chinese/attachments/20060605/00035e04/attachment.html

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

2006年06月05日 星期一 19:57

莫千聪 moqiancong at gmail.com
Mon Jun 5 19:57:08 HKT 2006

也可以试一下这个方法,

import string
bmap=('0', '1', '10', '11', '100', '101', '110', '111', '1000', '1001',
'1010', '1011', '1100', '1101', '1110', '1111')
def bin(num):
return "".join((bmap[string.atoi(x,16)] for x in "%x"%num))


Leo Jay 写道:
> 大家好。
> 今天琢磨了一下怎么把一个整数转为2进制。
> 把我的解法共享给大家看看,抛砖引玉,看看有没有更好的解法 ;)
>
> import math
>
> # 把整数转为2进制。只处理非负数
> def bin(num):
> if num == 0:
> return '0'
> return "".join([str((num>>i)&1) for i in
> xrange(int(math.floor(math.log(num, 2))),-1,-1)])
>
> for i in xrange(20):
> print bin(i)
>
> 运行的结果是这样的:
> 0
> 1
> 10
> 11
> 100
> 101
> 110
> 111
> 1000
> 1001
> 1010
> 1011
> 1100
> 1101
> 1110
> 1111
> 10000
> 10001
> 10010
> 10011
>
> -- 
> Best Regards,
> Leo Jay
> ------------------------------------------------------------------------
>
> _______________________________________________
> python-chinese
> Post: send python-chinese at lists.python.cn
> Subscribe: send subscribe to python-chinese-request at lists.python.cn
> Unsubscribe: send unsubscribe to  python-chinese-request at lists.python.cn
> Detail Info: http://python.cn/mailman/listinfo/python-chinese

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.exoweb.net/pipermail/python-chinese/attachments/20060605/834046a8/attachment.html

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

2006年06月05日 星期一 20:37

莫千聪 moqiancong at gmail.com
Mon Jun 5 20:37:12 HKT 2006

经测试,下面这个代码速度能更快些:
bmap=('0', '1', '10', '11', '100', '101', '110', '111', '1000', '1001',
'1010', '1011', '1100', '1101', '1110', '1111')
hexmap={ '0':0, '1':1, '2':2,'3':3,'4':4,'5':5, '6':6, '7':7, '8':8,
'9':9, 'a':10, 'b':11,'c':12, 'd':13, 'e':14,'f':15}

def bin(num):
return "".join((bmap[hexmap[x]] for x in "%x"%num))

Leo Jay 写道:
> 大家好。
> 今天琢磨了一下怎么把一个整数转为2进制。
> 把我的解法共享给大家看看,抛砖引玉,看看有没有更好的解法 ;)
>
> import math
>
> # 把整数转为2进制。只处理非负数
> def bin(num):
> if num == 0:
> return '0'
> return "".join([str((num>>i)&1) for i in
> xrange(int(math.floor(math.log(num, 2))),-1,-1)])
>
> for i in xrange(20):
> print bin(i)
>
> 运行的结果是这样的:
> 0
> 1
> 10
> 11
> 100
> 101
> 110
> 111
> 1000
> 1001
> 1010
> 1011
> 1100
> 1101
> 1110
> 1111
> 10000
> 10001
> 10010
> 10011
>
> -- 
> Best Regards,
> Leo Jay
> ------------------------------------------------------------------------
>
> _______________________________________________
> python-chinese
> Post: send python-chinese at lists.python.cn
> Subscribe: send subscribe to python-chinese-request at lists.python.cn
> Unsubscribe: send unsubscribe to  python-chinese-request at lists.python.cn
> Detail Info: http://python.cn/mailman/listinfo/python-chinese

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.exoweb.net/pipermail/python-chinese/attachments/20060605/572e2fb6/attachment.htm

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

2006年06月05日 星期一 20:50

莫千聪 moqiancong at gmail.com
Mon Jun 5 20:50:17 HKT 2006

呵呵,才发现自己犯糊涂病了,其实一步映射就可以的..不好意思..
hexmap={ '0':'0',
'1':'1',
'2':'10',
'3':'11',
'4':'100',
'5':'101',
'6':'110',
'7':'111',
'8':'1000',
'9':'1001',
'a':'1010',
'b':'1011',
'c':'1100',
'd':'1101',
'e':'1110',
'f':'1111'}
def bin(num):
return "".join((hexmap[x] for x in "%x"%num))

Leo Jay 写道:
> 大家好。
> 今天琢磨了一下怎么把一个整数转为2进制。
> 把我的解法共享给大家看看,抛砖引玉,看看有没有更好的解法 ;)
>
> import math
>
> # 把整数转为2进制。只处理非负数
> def bin(num):
> if num == 0:
> return '0'
> return "".join([str((num>>i)&1) for i in
> xrange(int(math.floor(math.log(num, 2))),-1,-1)])
>
> for i in xrange(20):
> print bin(i)
>
> 运行的结果是这样的:
> 0
> 1
> 10
> 11
> 100
> 101
> 110
> 111
> 1000
> 1001
> 1010
> 1011
> 1100
> 1101
> 1110
> 1111
> 10000
> 10001
> 10010
> 10011
>
> -- 
> Best Regards,
> Leo Jay
> ------------------------------------------------------------------------
>
> _______________________________________________
> python-chinese
> Post: send python-chinese at lists.python.cn
> Subscribe: send subscribe to python-chinese-request at lists.python.cn
> Unsubscribe: send unsubscribe to  python-chinese-request at lists.python.cn
> Detail Info: http://python.cn/mailman/listinfo/python-chinese

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.exoweb.net/pipermail/python-chinese/attachments/20060605/db1fc37e/attachment.html

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

2006年06月05日 星期一 21:02

Weifeng Qian nokia_qian at yahoo.com.cn
Mon Jun 5 21:02:39 HKT 2006

退定!

Leo Jay <python.leojay at gmail.com> 写道:    大家好。
  今天琢磨了一下怎么把一个整数转为2进制。
  把我的解法共享给大家看看,抛砖引玉,看看有没有更好的解法  ;)
    import math
  # 把整数转为2进制。只处理非负数
def bin(num):
 if num == 0:
  return '0'
 return "".join([str((num>>i)&1) for i in xrange(int(math.floor(math.log(num, 2))),-1,-1)])
  for i in xrange(20):
 print bin(i)

  运行的结果是这样的:
  0
1
10
11
100
101
110
111
1000
1001
1010
1011
1100
1101
1110
1111
10000
10001
10010
10011
  
-- 
Best Regards,
Leo Jay 
_______________________________________________
python-chinese
Post: send python-chinese at lists.python.cn
Subscribe: send subscribe to python-chinese-request at lists.python.cn
Unsubscribe: send unsubscribe to python-chinese-request at lists.python.cn
Detail Info: http://python.cn/mailman/listinfo/python-chinese

 __________________________________________________
赶快注册雅虎超大容量免费邮箱?
http://cn.mail.yahoo.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.exoweb.net/pipermail/python-chinese/attachments/20060605/7ed91c10/attachment.htm

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

2006年06月05日 星期一 22:25

Bruce Wang number5 at gmail.com
Mon Jun 5 22:25:04 HKT 2006

On 6/5/06, Leo Jay <python.leojay at gmail.com> wrote:
>
> 大家好。
> 今天琢磨了一下怎么把一个整数转为2进制。
> 把我的解法共享给大家看看,抛砖引玉,看看有没有更好的解法  ;)
>
> import math
>
> # 把整数转为2进制。只处理非负数
> def bin(num):
>  if num == 0:
>   return '0'
>  return "".join([str((num>>i)&1) for i in xrange(int(math.floor(math.log(num,
> 2))),-1,-1)])
>
> for i in xrange(20):
>  print bin(i)
> 运行的结果是这样的:
> 0
> 1
> 10
> 11
> 100
> 101
> 110
> 111
> 1000
> 1001
> 1010
> 1011
> 1100
> 1101
> 1110
> 1111
>


>>> def bin(n):
...     if (n==0):
...         return '0'
...     s = ''
...     while (n>0):
...         b = n & 1
...         s = str(b) + s
...         n = n >> 1
...     return s


-- 
simple is good
http://brucewang.net
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.exoweb.net/pipermail/python-chinese/attachments/20060605/9709af1a/attachment.htm

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

2006年06月06日 星期二 08:08

莫千聪 moqiancong at gmail.com
Tue Jun 6 08:08:08 HKT 2006

hexmap={ '0':'0000',
'1':'0001',
'2':'0010',
'3':'0011',
'4':'0100',
'5':'0101',
'6':'0110',
'7':'0111',
'8':'1000',
'9':'1001',
'a':'1010',
'b':'1011',
'c':'1100',
'd':'1101',
'e':'1110',
'f':'1111'}
def bin(num):
return "".join((hexmap[x] for x in "%x"%num)).lstrip('0')

这才是对的,上面写错了。。

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

2006年06月06日 星期二 21:05

Shixin Zeng zeng.shixin at gmail.com
Tue Jun 6 21:05:09 HKT 2006

On 6/6/06, 莫千聪 <moqiancong at gmail.com> wrote:
>
> hexmap={ '0':'0000',
> '1':'0001',
> '2':'0010',
> '3':'0011',
> '4':'0100',
> '5':'0101',
> '6':'0110',
> '7':'0111',
> '8':'1000',
> '9':'1001',
> 'a':'1010',
> 'b':'1011',
> 'c':'1100',
> 'd':'1101',
> 'e':'1110',
> 'f':'1111'}
> def bin(num):
> return "".join((hexmap[x] for x in "%x"%num)).lstrip('0')
>
> 这才是对的,上面写错了。。


这个也会有点小问题的:0x1f会写成00011111,而不是11111

_______________________________________________
> python-chinese
> Post: send python-chinese at lists.python.cn
> Subscribe: send subscribe to python-chinese-request at lists.python.cn
> Unsubscribe: send unsubscribe to  python-chinese-request at lists.python.cn
> Detail Info: http://python.cn/mailman/listinfo/python-chinese
>



-- 
Best Regards

Shixin Zeng
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.exoweb.net/pipermail/python-chinese/attachments/20060606/79a2cd2e/attachment.htm

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

2006年06月06日 星期二 21:12

莫千聪 moqiancong at gmail.com
Tue Jun 6 21:12:16 HKT 2006

An HTML attachment was scrubbed...
URL: http://lists.exoweb.net/pipermail/python-chinese/attachments/20060606/e4304004/attachment.htm

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

2006年06月06日 星期二 21:33

Shixin Zeng zeng.shixin at gmail.com
Tue Jun 6 21:33:00 HKT 2006

On 6/6/06, 莫千聪 <moqiancong at gmail.com> wrote:
>
>  呵呵,"".join((hexmap[x] for x in "%x"%num)).lstrip('0')
> 这句结尾有.lstrip('0'),不会出现你说的问题的。
>

实在是不好意思,我是昨天看到你前面的邮件,就觉得有问题,后面太晚了,就没回了。以为今天你只是把"0"改成了"0000"……,后面的看都没看了,实在是不应该啊。


Shixin Zeng 写道:
>
>
>
> On 6/6/06, 莫 千聪 <moqiancong at gmail.com> wrote:
> >
> > hexmap={ '0':'0000',
> > '1':'0001',
> > '2':'0010',
> > '3':'0011',
> > '4':'0100',
> > '5':'0101',
> > '6':'0110',
> > '7':'0111',
> > '8':'1000',
> > '9':'1001',
> > 'a':'1010',
> > 'b':'1011',
> > 'c':'1100',
> > 'd':'1101',
> > 'e':'1110',
> > 'f':'1111'}
> > def bin(num):
> > return "".join((hexmap[x] for x in "%x"%num)).lstrip('0')
> >
> > 这才是对的,上面写错了。。
>
>
> 这个也会有点小问题的:0x1f会写成00011111,而不是11111
>
> _______________________________________________
> > python-chinese
> > Post: send python-chinese at lists.python.cn
> > Subscribe: send subscribe to python-chinese-request at lists.python.cn
> > Unsubscribe: send unsubscribe to  python-chinese-request at lists.python.cn
> > Detail Info: http://python.cn/mailman/listinfo/python-chinese
> >
>
>
>
> --
> Best Regards
>
> Shixin Zeng
>
> ------------------------------
>
> _______________________________________________ python-chinese Post: send
> python-chinese at lists.python.cn Subscribe: send subscribe to
> python-chinese-request at lists.python.cn Unsubscribe: send unsubscribe to
> python-chinese-request at lists.python.cn Detail Info:
> http://python.cn/mailman/listinfo/python-chinese
>
>
> _______________________________________________
> python-chinese
> Post: send python-chinese at lists.python.cn
> Subscribe: send subscribe to python-chinese-request at lists.python.cn
> Unsubscribe: send unsubscribe to  python-chinese-request at lists.python.cn
> Detail Info: http://python.cn/mailman/listinfo/python-chinese
>
>


-- 
Best Regards

Shixin Zeng
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.exoweb.net/pipermail/python-chinese/attachments/20060606/34c37ddc/attachment.htm

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

2006年06月06日 星期二 21:39

莫千聪 moqiancong at gmail.com
Tue Jun 6 21:39:39 HKT 2006

An HTML attachment was scrubbed...
URL: http://lists.exoweb.net/pipermail/python-chinese/attachments/20060606/9acca64d/attachment.html

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

2006年06月06日 星期二 21:42

=?ISO-2022-JP?B?GyRCcjJDaRsoQg==?= weizhong2004 at gmail.com
Tue Jun 6 21:42:27 HKT 2006

这个没有问题. 因为最后使用了 ltrip('0')

-- 
开飞机的舒克
http://www.lvye.org/shuke
msn:weizhong at netease.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.exoweb.net/pipermail/python-chinese/attachments/20060606/be865926/attachment.htm

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

2006年06月06日 星期二 23:34

Leo Jay python.leojay at gmail.com
Tue Jun 6 23:34:54 HKT 2006

On 6/6/06, 魏忠 <weizhong2004 at gmail.com> wrote:
>
>
> 这个没有问题. 因为最后使用了 ltrip('0')
>
> 嗯。不过用ltrip("0")的话,那bin(0)就不对了。返回是空,呵呵。


-- 
Best Regards,
Leo Jay
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.exoweb.net/pipermail/python-chinese/attachments/20060606/d9151b70/attachment.html

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

2006年06月07日 星期三 08:34

莫千聪 moqiancong at gmail.com
Wed Jun 7 08:34:51 HKT 2006

An HTML attachment was scrubbed...
URL: http://lists.exoweb.net/pipermail/python-chinese/attachments/20060607/42c67c66/attachment.html

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

2006年06月07日 星期三 08:42

魏忠 weizhong2004 at gmail.com
Wed Jun 7 08:42:19 HKT 2006

那就再改进一下 :)
return ''.join((hexmap[x] for x in "%x"%num)).lstrip('0') or '0'



-- 
开飞机的舒克
http://www.lvye.org/shuke
msn:weizhong at netease.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.exoweb.net/pipermail/python-chinese/attachments/20060607/cbc7c3f4/attachment.html

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

2006年06月07日 星期三 13:23

莫千聪 moqiancong at gmail.com
Wed Jun 7 13:23:54 HKT 2006

魏忠 写道:
>
> 那就再改进一下 :)
> return ''.join((hexmap[x] for x in "%x"%num)).lstrip('0') or '0'
>
>
呵呵,改得好。

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

2006年06月07日 星期三 14:48

waterfeel aninfeel at gmail.com
Wed Jun 7 14:48:19 HKT 2006

在06-6-7,魏忠 <weizhong2004 at gmail.com> 写道:
>
>
> 那就再改进一下 :)
> return ''.join((hexmap[x] for x in "%x"%num)).lstrip('0') or '0'
>
>
>
>
> --
> 开飞机的舒克
> http://www.lvye.org/shuke
> msn:weizhong at netease.com
>
> _______________________________________________
> python-chinese
> Post: send python-chinese at lists.python.cn
> Subscribe: send subscribe to python-chinese-request at lists.python.cn
> Unsubscribe: send unsubscribe to  python-chinese-request at lists.python.cn
> Detail Info: http://python.cn/mailman/listinfo/python-chinese
>
> 8421bcd码也可以吧
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.exoweb.net/pipermail/python-chinese/attachments/20060607/dc7894f4/attachment.htm

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

2006年06月07日 星期三 14:52

he huang huanghe1860 at msn.com
Wed Jun 7 14:52:26 HKT 2006

# -*- coding: cp936 -*-
# bstr_pos: only positive integers
# zero     -> ''
# negative -> ''
B2 = "01"
B10 = "0123456789"
B16 = "0123456789ABCDEF"
BASE62 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz"

def baseconvert(number,fromdigits,todigits):
    """ converts a "number" between two bases of arbitrary digits

    The input number is assumed to be a string of digits from the
    fromdigits string (which is in order of smallest to largest
    digit). The return value is a string of elements from todigits
    (ordered in the same way). The input and output bases are
    determined from the lengths of the digit strings. Negative
    signs are passed through.

    decimal to binary
    >>> baseconvert(555,BASE10,BASE2)
    '1000101011'

    binary to decimal
    >>> baseconvert('1000101011',BASE2,BASE10)
    '555'

    integer interpreted as binary and converted to decimal (!)
    >>> baseconvert(1000101011,BASE2,BASE10)
    '555'

    base10 to base4
    >>> baseconvert(99,BASE10,"0123")
    '1203'

    base4 to base5 (with alphabetic digits)
    >>> baseconvert(1203,"0123","abcde")
    'dee'

    base5, alpha digits back to base 10
    >>> baseconvert('dee',"abcde",BASE10)
    '99'

    decimal to a base that uses A-Z0-9a-z for its digits
    >>> baseconvert(257938572394L,BASE10,BASE62)
    'E78Lxik'

    ..convert back
    >>> baseconvert('E78Lxik',BASE62,BASE10)
    '257938572394'

    binary to a base with words for digits (the function cannot convert this 
back)
    >>> baseconvert('1101',BASE2,('Zero','One'))
    'OneOneZeroOne'

    """

    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
bstr_pos = lambda n: n>0 and bstr_pos(n>>1)+str(n&1) or ''

# bstr_nonneg: only non-negative integers
# zero     -> '0'
# negative -> ''

bstr_nonneg = lambda n: n>0 and bstr_nonneg(n>>1).lstrip('0')+str(n&1) or 
'0'

# bstr_sgn: all integers, signed
# zero -> '0'
# negative get a minus sign

bstr_sgn = lambda n: n<0 and '-'+binarystr(-n) or n and 
bstr_sgn(n>>1).lstrip('0')+str(n&1) or '0'

# bstr: all integers
# zero -> '0'
# negative represented as complements, 16-bit by default
# optional second argument specifies number of bits

bstr = lambda n, l=16: n<0 and binarystr((2L<>1).lstrip('0')+str(n&1) or '0'

print baseconvert(1000101011,B2,B10)
a='FE FD FE 00 00 22 2A 00 00 A6 01 4F 79 03 09 1F 0C 08 FF 00 00 FF E9 03 
4D 69 66 61 72 65 5A 68 61 6F 10 27 00 00 00 00 00 00 12 01 06 31 32 33 34 
4C'
l=a.split()
print l[1]
a=int("FF9C", 16)
print hex(-1000)
print a
print bstr (a)
print bstr_sgn(a)
print bstr_pos(a)
print bstr_nonneg(a)
print int("03E9", 16)
print int("07d1", 16)
print int("03EE", 16)
import binascii
print binascii.b2a_hex('EMEMEMEM»ÆºÍ')
print binascii.a2b_hex('6c656f')
print '_________'


»ÆºÓ

_________________________________________________________________
Don't just search. Find. Check out the new MSN Search! 
http://search.msn.com/


[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

如下红色区域有误,请重新填写。

    你的回复:

    请 登录 后回复。还没有在Zeuux哲思注册吗?现在 注册 !

    Zeuux © 2025

    京ICP备05028076号