問題描述
如何在 Python 中將二進制字符串轉(zhuǎn)換為對應(yīng)的十六進制值?
我有 0000 0100 1000 1101
我想獲得 048D
我正在使用 Python 2.6.
int
給定 base 2 然后 hex
:
>>>整數(shù)('010110',2)22>>>十六進制(整數(shù)('010110',2))'0x16'>>>>>>十六進制(整數(shù)('0000010010001101',2))'0x48d'
int
的文檔:
int(x[, base]) ->整數(shù)如果可能,將字符串或數(shù)字轉(zhuǎn)換為整數(shù).一個漂浮的
點參數(shù)將被截斷為零(這不包括字符串浮點數(shù)的表示!)轉(zhuǎn)換字符串時,利用可選基地.轉(zhuǎn)換 a 時提供堿基是錯誤的非字符串.如果基數(shù)為零,則根據(jù)字符串內(nèi)容.如果參數(shù)超出整數(shù)范圍將改為返回長對象.
hex
的文檔:
十六進制(數(shù)字)->細繩返回整數(shù)或長整數(shù)的十六進制表示
整數(shù).
How can I perform a conversion of a binary string to the corresponding hex value in Python?
I have 0000 0100 1000 1101
and I want to get 048D
I'm using Python 2.6.
int
given base 2 and then hex
:
>>> int('010110', 2)
22
>>> hex(int('010110', 2))
'0x16'
>>>
>>> hex(int('0000010010001101', 2))
'0x48d'
The doc of int
:
int(x[, base]) -> integer Convert a string or number to an integer, if possible. A floating
point argument will be truncated towards zero (this does not include a string representation of a floating point number!) When converting a string, use the optional base. It is an error to supply a base when converting a non-string. If base is zero, the proper base is guessed based on the string content. If the argument is outside the integer range a long object will be returned instead.
The doc of hex
:
hex(number) -> string Return the hexadecimal representation of an integer or long
integer.
這篇關(guān)于Python從二進制字符串轉(zhuǎn)換為十六進制的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!