MyHDL

How to do signed operations on intbv

I am trying to implement a simple ALU with add and subtract operations. I got an error once the resulted value is less than 0!

Can anyone provide me with an example of how to do it correctly in MyHDL?
Thank you in advance

I guess you have declared your accumulator as Signal(intbv(0)[8:])
This implies that only positive values can be assigned to this signal.
In order to allow for negative values you need to declare it this way: Signal(intbv(0, min=-128, max=128))
This may not the effective solution for an 8-bit accumulator as you probably also want to accommodate 8-bit unsigned values. So it is better to resolve this by using unsigned two’s arithmetic and declaring the accumulator as Signal(modbv(0)[8:]) and work with this.
I hope this sets you on your way.

Regards,
Josy

Here is my code. It seems that the intbv is okay, but when the value is assigned to the Signal of type intbv the problem is araised.

@block
def ALU(rs1, rs2, op, out):
  outX = intbv(0, min=-2**31, max=2**31-1)
  print(outX.min, len(outX))

  @always_comb
  def logic():
    if op == 0b0000:
      outX = rs1 + rs2
    elif op == 0b0001:
      outX = rs1.val - rs2.val
    else:
      outX = 0b0
    
    out.next = outX   #The problem arises in this line
  return logic

@block
def Stimulus():
  clk    = Signal(bool(0))
  rs1    = Signal(intbv(0, min=-2**31, max=(2**31)-1)[32:])
  rs2    = Signal(intbv(0, min=-2**31, max=(2**31)-1)[32:])
  op     = Signal(intbv(0)[4:])
  Result = Signal(intbv(0, min=-2**31, max=(2**31)-1)[32:])

  ALU_1 = ALU(rs1, rs2, op, Result)

  @always(delay(10))
  def clk_driver():
    rs1.next = rs1 + 1
    rs2.next = rs2 + 10
    print('Results = %d'% Result)
    op.next = 0b1

  return instances()
if __name__ == '__main__':
    inst = Stimulus()
    inst.run_sim(300)

Thank you again for helping out.

you instantiate it as: outX = intbv(0, min=-2**31, max=2**31)
The max value excludes the upper value