Solidity – Math Operations Between int and uint Explained

contract-developmentsolidity

How is it possible to either convert uint to int or do simple math comparison operations?

Something like:

uint a;
uint b;
int c;


if (a - b < c) doSomething();

What I'm trying to do is to see if the subtraction of two integers are negative or not. however one of those values comes from msg.value so it should be uint, and I'm not sure if we do uint – uint the result could smaller than 0 to check it on if condition.

Best Answer

To convert one type to another, use uint(x) or int(x). The rules are basically the same as in C, where the first bit of the uint becomes the sign.

For example:

if (int(a - b) < c) doSomething();

is likely what you want, as the numbers will be subtracted, then converted.

The type(x) syntax is used for all kinds of casting, such as truncating a number (uint8(someUint)), converting to and from odd types (bytes32(someUint)), or even casting a given address to a specific contract type (someContract(someAddress)).

Related Topic