如何创建或解释自定义数据类型(4位签名)

时间:2015-02-17 01:55:49

标签: python signed custom-data-type

用于计算我需要一些自定义大小的变量(例如“int4_t”),我想知道我是否可以使用ctypes轻松完成此操作。 修改 我在这里找到了一个解决方案:how-to-emulate-4-bit-integer-in-python-3 我在底部使用了python 2.x的答案,但我不知道要改变什么来签名变量,我需要它来计算和限制输入。

提前谢谢!

1 个答案:

答案 0 :(得分:0)

def getSignedNumber(number, bitLength):
    mask = (2 ** bitLength) - 1
    if number & (1 << (bitLength - 1)):
        return number | ~mask
    else:
        return number & mask

print iv, '->', getSignedNumber(iv, 32)

这是将期望值作为int返回,使用自定义bitlength并且很短。我在底部找到它:how-to-get-the-signed-integer-value-of-a-long-in-python

修改

print 10, '->', getSignedNumber(10, 4), type(getSignedNumber(10, 4)),getSignedNumber(10, 4)*500000, bin(getSignedNumber(10, 4))
print 15, '->', getSignedNumber(15, 4), type(getSignedNumber(15, 4)),getSignedNumber(15, 4)*500000, bin(getSignedNumber(15, 4))
print 9, '->', getSignedNumber(9, 4), type(getSignedNumber(9, 4)),getSignedNumber(9, 4)*500000, bin(getSignedNumber(9, 4))
print 8, '->', getSignedNumber(8, 4), type(getSignedNumber(8, 4)),getSignedNumber(8, 4)*500000, bin(getSignedNumber(8, 4))
print 7, '->', getSignedNumber(7, 4), type(getSignedNumber(7, 4)),getSignedNumber(7, 4)*500000, bin(getSignedNumber(7, 4))

这都导致了正确的int但是当我检查二进制数据时它完全错误(-1 = -0b1应该是-0b111,-6 = -0b110应该是-0b010,这怎么可能?)所以我需要重新打开这个问题......

<强>解决方案:

def intX_raw(value,sign_bit):
  max_pos=(2**(sign_bit-1))-1  # maximum positive val
  max_neg=(-max_pos)-1
  max_val=(max_pos + (-max_neg))
  print "max positive:",max_pos
  print "max negative:",max_neg
  print "max possible:",max_val
  if value>max_val:
    print"Value too high for int%d"%sign_bit,value
    return 255
  if value<0:
    diff=abs(max_neg+(-value))+1
    result=max_pos+diff
    return result
  else: return value

def intX_val(value,sign_bit):
  max_pos=(2**(sign_bit-1))-1  # maximum positive val
  max_neg=(-max_pos)-1
  max_val=(max_pos + (-max_neg))
  print "max positive:",max_pos
  print "max negative:",max_neg
  print "max possible:",max_val
  if value>max_val:
    print"Value too high for int%d"%sign_bit,value
    return 255

  if value>max_pos:
    print "val over max_pos:",value
    diff=value-max_pos
    result=max_neg+(diff-1)
    return result
  else: return value