I have an int32 val that contains some negative value such as -1. I want to multiply it with a uint32 value and add a larger uint32 value (for which I know the result will be positive) and store in uint32.
I have come up with the following solution:
uint32 result = uint32( uint32(i) * val + 100)
For example: i=-1, val=10, result should be (-1)*(10) + 100 = 90.
[Q] Is this the correct way to do it?
Since I am casting a signed int to an unsigned int as ( uint32(i) ), shouldn't a negative value (-1) get automatically converted into positive (+1) and give a result of (+1)*(10) + 100 = 110?
pragma solidity ^0.4.6;
contract NumTest {
int8 i;
function NumTest() {
i = -1;
}
function number() constant returns (uint32 num) {
uint32 val = 3;
return uint32( uint32(i) * val + 20);
}
}
-1to+1directly. – Richard Horrocks Feb 22 '17 at 17:50