Skip to content

Signed math on Cat gives incorrect results #473

Closed
@pepijndevos

Description

@pepijndevos

Consider the following minimal example:

from nmigen import *
from nmigen.sim.pysim import *

def resolve(expr):
    sim = Simulator(Module())
    a = []
    def testbench():
        a.append((yield expr))
    sim.add_process(testbench)
    sim.run()
    return a[0]

sig = Const(-3, 8)
print(sig, sig.shape())
print(bin(resolve(sig)))
print(bin(resolve(-sig)))

sig2 = Cat(sig).as_signed()
print(sig2, sig2.shape())
print(bin(resolve(sig2)))
print(bin(resolve(-sig2)))

Which prints

(const 8'sd-3) signed(8)
-0b11
0b11
(s (cat (const 8'sd-3))) signed(8)
-0b11
-0b11111101

Of course python's binary representation is a bit misleading here. -0b11 should actually be 0b111...1101 in two's complement.
So actually -0b11111101 would be 0b1111...1100000011 IIRC, which is 3 except not sign-extended.

So it appears that when you put a signed number in a Cat and convert that to signed, the result is not sign-extended correctly.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions