# python之二进制和十进制转换

belukwill 2012-06-05 03:07:07

``````
bin=str(input('输入二进制数：'))
count = 0
for i in range(0,len(bin)):
if bin[i] == str(1):
sum=2**(len(bin)-i-1)
count=count+sum
print count
``````

``````
number = int(input('输入十进制'))
n=''.join([str((number>>a&0x1))for a in range(7,-1,-1)]);
print n
``````
...全文
2900 8 打赏 收藏 举报

8 条回复

huaoweiomian 2014-01-28
• 打赏
• 举报

huer0625 2012-06-27
• 打赏
• 举报

int(x[, base]) -> integer
panghuhu250 2012-06-27
• 打赏
• 举报

``````
In [21]: def bin2dec(s):
...:     total = 0
...:     for i in s:
...:         total = 2*total + (0 if i=='0' else 1)

In [22]: def bin2dec2(bin):
...:     count = 0
...:     for i in range(0,len(bin)):
...:         if bin[i] == str(1):
...:             sum=2**(len(bin)-i-1)
...:             count=count+sum
...:     return count

In [23]: a = '101010101010111'

In [24]: int(a, 2)
Out[24]: 21847

In [25]: bin2dec(a)
Out[25]: 21847

In [26]: bin2dec2(a)
Out[26]: 21847

In [27]: %timeit int(a, 2)
10000000 loops, best of 3: 181 ns per loop

In [28]: %timeit bin2dec(a)
1000000 loops, best of 3: 1.36 us per loop

In [29]: %timeit bin2dec2(a)
100000 loops, best of 3: 4.55 us per loop
``````
Rlay_2 2012-06-06
• 打赏
• 举报

``````
x = bin(1024)
print 'bin:', x

x = oct(1024)
print 'oct:', x

x = hex(1024)
print 'hex:', x

bin: 0b10000000000
oct: 02000
hex: 0x400
``````

angel_su 2012-06-06
• 打赏
• 举报

belukwill 2012-06-06
• 打赏
• 举报

aaseh 2012-06-05
• 打赏
• 举报

bugs2k 2012-06-05
• 打赏
• 举报

``````[GCC 4.6.3] on linux2
>>> bin(7)
'0b111'
>>> int(0b111)
7
>>>
``````

3.7w+

JavaScript，VBScript，AngleScript，ActionScript，Shell，Perl，Ruby，Lua，Tcl，Scala，MaxScript 等脚本语言交流。

2012-06-05 03:07