0

我在 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)

此代码应返回值0118CA

4

1 回答 1

3

我会写得更像这样:

def int_to_hex_string(value, bits):
    return "{0:0{1}X}".format(value & ((1<<bits) - 1), bits//4)

if __name__ == '__main__':
  x, y = 280, -54
  print(int_to_hex_string(x, 16), int_to_hex_string(y, 8))

我认为您的类型检查不会添加任何内容:如果值不是正确的类型,您将通过不检查获得更合适的“TypeError”,同样将“int16”和“int8”作为 16 和 8 的别名真的不要加太多。

于 2013-05-07T19:43:15.780 回答