1

for calculation i need some variables to be custom sized (eg. "int4_t") and i wonder if i can do this easily with ctypes. EDIT: I found a solution here: how-to-emulate-4-bit-integer-in-python-3 I used the answer at the bottom for python 2.x but i can´t find out what to change to have a signed variable, i need it for calculation and restricting entry input.

Thx in advance!

Community
  • 1
  • 1
Marc Pole
  • 29
  • 7

1 Answers1

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)

This is returning the expected value as int, works with custom bitlength and is pretty short.I found it at the bottom here :how-to-get-the-signed-integer-value-of-a-long-in-python

EDIT:

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

This all results into the right int but when i check the binary data it´s completely wrong (-1=-0b1 should be -0b111, -6=-0b110 should be -0b010, how can this be ?) so i need to reopen the question again...

Solution:

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
Community
  • 1
  • 1
Marc Pole
  • 29
  • 7