十进制,十六进制转换的python程序(显示二进制)
时间:2010-03-06 来源:mishuang
以前用Shell写过个类似的程序,总觉得别扭,现在发现python还是蛮强大的。
#!/usr/bin/python
import re
import sys
import string
argv1 = sys.argv[1]
if re.match('^(0x|0X)', argv1) or re.search('([a-fA-F]+)', argv1):
i = string.atoi(argv1, base=16)
elif re.match('^\d+$', argv1):
i = string.atoi(argv1, base=10)
else:
print "Error input!"
exit()
r=''
n = 0x80000000
while n:
r += '1' if n & i else '0'
if len(re.sub(' ', '', r)) % 4 == 0:
r += ' '
n >>= 1
print '0x%x = %d = %.2fK =' % (i, i, i / 1024.0),
print '%.2fM = %.2fG' % (i / 1024.0 ** 2.0, i / 1024.0 ** 3.0)
print r
$ alias x='/export/home/mishuang/prg/python/x.py'
$ prtconf | grep Mem
Memory size: 1511 Megabytes
$ x 1511
0x5e7 = 1511 = 1.48K = 0.00M = 0.00G
0000 0000 0000 0000 0000 0101 1110 0111
$ x 0xdf8fffff
0xdf8fffff = 3750756351 = 3662848.00K = 3577.00M = 3.49G
1101 1111 1000 1111 1111 1111 1111 1111
$ x df8fffff
0xdf8fffff = 3750756351 = 3662848.00K = 3577.00M = 3.49G
1101 1111 1000 1111 1111 1111 1111 1111
#!/usr/bin/python
import re
import sys
import string
argv1 = sys.argv[1]
if re.match('^(0x|0X)', argv1) or re.search('([a-fA-F]+)', argv1):
i = string.atoi(argv1, base=16)
elif re.match('^\d+$', argv1):
i = string.atoi(argv1, base=10)
else:
print "Error input!"
exit()
r=''
n = 0x80000000
while n:
r += '1' if n & i else '0'
if len(re.sub(' ', '', r)) % 4 == 0:
r += ' '
n >>= 1
print '0x%x = %d = %.2fK =' % (i, i, i / 1024.0),
print '%.2fM = %.2fG' % (i / 1024.0 ** 2.0, i / 1024.0 ** 3.0)
print r
$ alias x='/export/home/mishuang/prg/python/x.py'
$ prtconf | grep Mem
Memory size: 1511 Megabytes
$ x 1511
0x5e7 = 1511 = 1.48K = 0.00M = 0.00G
0000 0000 0000 0000 0000 0101 1110 0111
$ x 0xdf8fffff
0xdf8fffff = 3750756351 = 3662848.00K = 3577.00M = 3.49G
1101 1111 1000 1111 1111 1111 1111 1111
$ x df8fffff
0xdf8fffff = 3750756351 = 3662848.00K = 3577.00M = 3.49G
1101 1111 1000 1111 1111 1111 1111 1111
相关阅读 更多 +