[Python] 各种转换

Hex -> Dec

假定16进制是字符串:

s = "6a48f82d8e828ce82b82"

就可以使用下面的表达式转换成整型:

i = int(s, 16)
# eg.
int("0xff", 16)
# output: 255
int("FFFF", 16)
# output: 65535

使用 str(i) 转换成十进制字符串。

Dec -> Hex

使用:

hex(dec).split('x')[-1]

后面的split('x')[-1]取消0x, 例如:

d = 30
hex(d).split('x')[-1]
# 输出 '1e'

或者

hex(dec)[2:]

string -> double

x = "2342.34"
float(x)
# 输出: 2342.3400000000001

Python 的float 相当于C 的 double

或者:

 from decimal import Decimal
x = "234243.434"
print Decimal(x)
#输出: 234243.434

float -> int

如果原始值为字符串,写成

int(float('20.0'))
# 输出20

binary -> int

可以使用:

int('11111111', 2)
# 255

int <-> string

str(10)
# 输出: '10'
int('10')
# 输出: 10

猜你喜欢

转载自blog.csdn.net/ftell/article/details/82115396
今日推荐