转载自:https://blog.youkuaiyun.com/weixin_40717096/article/details/80199257
作者:Hello-Adam
1. 各个进制的符号:
- b:二进制;
- o:八进制;
- d:十进制;
- x:十六进制
在python中,bin(),oct(),hex()返回值均为字符串而且会带有0b,0o,0o前缀
2. 各个进制相互转换
a)十进制转换二进制:
十进制转换二进制:
#coding=utf-8
s = 10
list_one = []
if s >= 0 and s <= 1:
print "二进制:%d"%(s)
else:
while s >= 1:
list_one.append(str(s % 2))
s = s / 2
#list_one.append(str(s))
list_one.reverse()
print ''.join(list_one)
b)十进制转换八进制:
十进制转换到八进制
#coding=utf-8
s = 10
list_one = []
if s >= 0 and s <= 1:
print "二进制:%d"%(s)
else:
while s >= 1:
list_one.append(str(s % 8))
s = s / 8
#list_one.append(str(s))
list_one.reverse()
print ''.join(list_one)
c)十进制到十六进制:
3. 从二,八,十六进制到转换到十进制
a)二进制到十进制:
b)八进制到十进制
c)十六进制到十进制
小结:这里用到格式化字符串函数format;还有eval函数。各个进制之间转换比较灵活不要只局限上面的方法;还可以利用我们的公式转换;也可以借用十进制作为中介。