有符号整数为二进制补码十六进制

时间:2013-05-07 19:32:37

标签: python hex twos-complement

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

1 个答案:

答案 0 :(得分:2)

我会写得更像这样:

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并没有真正增加太多。