Add ValueInt.from_bits() for signed/unsigned bit pattern conversion
Hardware interface values stored in ValueInt are misinterpreted in Python—bit patterns from DUT registers are always treated as unsigned, breaking signed value semantics.
Changes
API Addition (src/vsc/model/value_scalar.py)
- Added
ValueInt.from_bits(value, width, signed=False)class method - Masks input to specified bit width
- Applies two's complement conversion when
signed=Trueand MSB is set
Tests (ve/unit/test_value_int.py)
- Covers 1/4/8/16/32-bit widths, masking, sign detection, edge cases
Documentation (doc/source/data_types.rst)
- New section: "Converting Bit Patterns to Values"
Usage
import vsc
# DUT returns 0xFFFFFFF0 from 32-bit signed register
dut_val = read_register()
python_val = vsc.ValueInt.from_bits(dut_val, width=32, signed=True)
# Result: -16 (not 4294967280)
# Unsigned interpretation
vsc.ValueInt.from_bits(0xFF, width=8, signed=False) # 255
# Signed interpretation
vsc.ValueInt.from_bits(0xFF, width=8, signed=True) # -1
Addresses #248
Original prompt
This section details on the original issue you should resolve
<issue_title>ValueInt class needs something like $signed method in SV</issue_title> <issue_description>So im using the value stored in an ValueInt object in python and the stored binary value which works correctly with dut interface always gets misinterpreted in Python world because python infers the given numbers as unsigend. I think having a $signed helper method in ValueInt class can be helpful to prevent such problems. I have currently implemented a $signed function in this way:
def signed(numb, width): if (numb >> (width-1)): return(-((2 ** width) - numb)) else: return numb
</issue_description>
<agent_instructions>Implement 'from_bits' as described in #248. Use the algorithm from the initial comment. Write tests to ensure value conversion (specifically, value masking, sign detection, and conversion) are implemented properly.</agent_instructions>
Comments on the Issue (you are @copilot in this section)
@mballance Useful idea, @Amirk97 . I'm wondering whether it would make sense to have this be a way to construct a ValueInt. For example:dut_val = <path> vsc_val = vsc.ValueInt.from_bits(dut_val, width=32, signed=True)Thoughts?</comment_new>
- Fixes fvutils/pyvsc#248
💬 We'd love your input! Share your thoughts on Copilot coding agent in our 2 minute survey.