4

我正在将十六进制数据转换为十进制,范围是从 00 到 FF

 hex_data = "FF"
int("0x" + hex_data , 16) 

返回 255,但是当我将 0 作为 hexdata 给出时,它会给出 0 而我需要它作为 000

怎么做

4

2 回答 2

7

您需要对其进行格式化:

hex_data = "FF"
number = int("0x" + hex_data, 16) 
print '%03d' % number # either this
print '{:03d}'.format(number) # or this (Python >= 2.6)
于 2012-09-07T11:48:27.877 回答
1

为了完整起见,您还可以执行以下操作:

str(int(hex_data, 16)).zfill(3)
于 2012-09-07T12:14:20.023 回答