Re: [myhdl-list] Slicing an unsigned intbv to a signed one
Brought to you by:
jandecaluwe
From: Günter D. <dan...@we...> - 2008-06-11 20:51:10
|
Jan Decaluwe wrote: ... > I'm now thinking aloud for the case you describe, sign-extension. > > The ideal solution might be if we could somehow give an addional > parameter to slicing, e.g. asking for "signed" slicing instead > of the default, unsigned. But I don't see how. We actually do that in the DeFixedInt class http://www.dilloneng.com/documents/downloads/demodel/ Similar to intbv for an instance of that class a bit width can be specified. The msb based on the specified width is considered the sign bit. The decision is made whether the msb is included in the slice or not. To quote from the doc string of the __getitem__ function: When the slice includes the sign bit it is taken over to the return value. If the sign bit is excluded the bits are taken as is with the sign bit set to 0. For example using the 4-bit number -6 = b1010, slicing bits 3:1 --> b101 includes the sign bit, the result is -3. Now using the 4-bit number -3 = b1101, slicing bits 2:1 --> b10, however, the slice excludes the sign bit, hence the result is 2. However, for the case of intbv I would not focus on where the bits come from, but rather where they should go to. So if the destination is supposed to be signed, then don't worry about where the bits come from. With a slice there is a fixed number of bits and depending on how this slice gets assigned to the destination should make the decision about the sign of the destination. So let's say the destination is a signed intbv with _nrbits set and the slice gets assigned to it. If that slice matches _nrbits and in the slice the msb is set, that should turn the value into a negative value. > > Another interesting way might be to introduce methods to intbv's > at this point. We could do this like for python strings: the > methods don't modify the object in-place, but instead return a > new object with the modified value. (In MyHDL tradition, > those intbv methods would return integers.) The advantage > of this approach (as opposed to creating new functions) > is that adding new methods doesn't pollute the myhdl > namespace further. In a way the sign extension could be done through the __setitem__ function. Basically the _min, _max attributes decide about how the value assigned is interpreted. If _min=0 the intbv instance is seen as unsigned. If _min = -_max the intbv instance is seen as signed and the assigned value is interpreted as signed with _nrbits specifying the msb and if that bit in the assigned value is set, the value is considered negative. That would allow to assign bit slices that come actually from unsigned values and convert to a signed value. I am probably overlooking something, but maybe some ideas are a starting point? Guenter |