Python hex() 函數(shù)用于將整數(shù)轉(zhuǎn)換為以“0x”為前綴的小寫十六進(jìn)制字符串:
print(hex(255)) # decimal十進(jìn)制
print(hex(0b111)) # binary二進(jìn)制
print(hex(0o77)) # octal八進(jìn)制
print(hex(0XFF)) # hexadecimal十六進(jìn)制
輸出:
0xff
0x7
0x3f
0xff
十六進(jìn)制 到 十進(jìn)制
使用 int() 函數(shù) ,第一個(gè)參數(shù)是字符串 ‘0Xff’ ,第二個(gè)參數(shù)是說(shuō)明,這個(gè)字符串是幾進(jìn)制的數(shù)。 轉(zhuǎn)化的結(jié)果是一個(gè)十進(jìn)制數(shù)。
>>> int('0xf',16)
15
二進(jìn)制 到 十進(jìn)制
>>> int('10100111110',2)
1342
八進(jìn)制 到 十進(jìn)制
>>> int('17',8)
15
其實(shí)可以看到,不管 幾進(jìn)制數(shù) 轉(zhuǎn)換成 十進(jìn)制數(shù) ,都是用 int() 函數(shù) 。之后后面的 第二個(gè)參數(shù) 寫清楚 前面字符串 是 幾進(jìn)制數(shù)就可以 。注意一定要合法。 比如2進(jìn)制數(shù)就不能出現(xiàn)2這樣的字符。
十進(jìn)制 轉(zhuǎn) 十六進(jìn)制
>>> hex(1033)
'0x409'
二進(jìn)制 轉(zhuǎn) 十六進(jìn)制
就是 二進(jìn)制先轉(zhuǎn)成 十進(jìn)制, 再轉(zhuǎn)成 十六進(jìn)制。
>>> hex(int('101010',2))
'0x2a'
八進(jìn)制到 十六進(jìn)制
就是 八進(jìn)制先轉(zhuǎn)成 十進(jìn)制, 再轉(zhuǎn)成 十六進(jìn)制。
>>> hex(int('17',8))
'0xf'
十進(jìn)制轉(zhuǎn)二進(jìn)制
>>> bin(10)
'0b1010'
十六進(jìn)制轉(zhuǎn) 二進(jìn)制
十六進(jìn)制->十進(jìn)制->二進(jìn)制
>>> bin(int('ff',16))
'0b11111111'
八進(jìn)制 到 二進(jìn)制
八進(jìn)制先到十進(jìn)制,再到二進(jìn)制
>>> bin(int('17',8))
'0b1111'
二進(jìn)制 到 八進(jìn)制
>>> oct(0b1010)
'012'
十進(jìn)制到八進(jìn)制
>>> oct(11)
'013'
十六進(jìn)制到八進(jìn)制文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-514576.html
>>> oct(0xf)
'017'
可見oct 函數(shù) 可將 任意進(jìn)制的數(shù) 轉(zhuǎn)換成 8進(jìn)制的。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-514576.html
到了這里,關(guān)于Python hex()十六進(jìn)制轉(zhuǎn)換的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!