How negative value in a registers are handled?
Could @bit-hack please explain how negative values in registers are handled? For example say ADDI r5, r0, 100 and say r0 has value -100 (in 2's complement) will following give correct answer ?
82 case 0: // ADDI Aidan Dodds, 20/09/20 16:10 • tidy and fix SRAI bug
1 rv->X[rd] = (int32_t)(rv->X[rs1]) + imm;
2 break;
because X stores unsigned integer AFAIU then above seems not handled correctly.
Hi Vivek,
The code above is correct.
The array of uint32_t X[32] for the register file is just a container for 32bit data. What's important here is that the operands are cast correctly prior to performing signed or unsigned operations.
In the example above, you can see that for the signed ADDI instruction, the value read from X[rs1] is cast to a signed integer, which means the operation is performing signed arithmetic. Once the operation is computed, its converted back to an unsigned result and stored away.
The bit pattern for signed and unsigned is the same so this is perfectly correct and fairly basic behavior in C. To get a better grasp of this, you could read up about casting and type promotion.
Remember, the key is not what type the data is stored as, but how its cast before the arithmetic is performed.
Don't we need to store negative numbers in 2' complement ? Also I don't think what above you described is true for Rust.
Don't we need to store negative numbers in 2' complement ?
The stored bit-pattern for signed and unsigned numbers is the same. What's important is how that data gets used during an operation. The data doesn't know that its signed or unsigned, only the operation does.
Also I don't think what above you described is true for Rust.
I have no idea about rust, I've never looked at it. What I described is valid for C and C++.
Don't we need to store negative numbers in 2' complement ?
Further to this point, the data will be stored in twos compliment, because the result of the operation was is signed. We do not modify the bit pattern of the result when storing it.