我在 Python 中编写了一个函数来获取有符号整数,使用二进制补码对其进行转换,然后返回十六进制值。我知道有一个hex()
函数,但我希望能够指定整数的大小。我怎样才能提高这段代码的质量并且我错过了什么?谢谢!
#!/usr/bin/python
int8, int16, int32, int64 = 8, 16, 32, 64
def intToHexString(value, bits):
def getBitmask(bits):
mask = 0
for i in range(bits):
mask = (mask << 1) + 1
return mask
if not isinstance(value, (int, long)):
raise ValueError("'%s' is not an Integer!"%str(value))
if not isinstance(bits, int) or bits % 2 != 0:
raise ValueError("Illegal integer size," +
"value %s must be divisible by 2!"%str(bits))
result = value
bitmask = getBitmask(bits)
halfMask = bitmask >> 1
minVal, maxVal = -halfMask, halfMask-1
if not minVal <= result <= maxVal:
raise ValueError('Out of range: %d <= %d <= %d'
%(minVal, result, maxVal))
if value < 0:
result = ((abs(value) ^ bitmask) + 1) & bitmask
return '%0*X'%(int(float(bits)/4), result)
if __name__ == '__main__':
x, y = 280, -54
print intToHexString(x, int16), intToHexString(y, int8)
此代码应返回值0118
和CA