23

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.

3 Answers 3

19

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)).

3
  • 2
    Frankly, there is no such rule in C, so basically this is nothing like C. In C the behaviour of casting an unsigned into signed where the value wouldn't be representable, would be undefined. Commented Mar 24, 2018 at 8:06
  • 1
    *casting => conversion Commented Mar 24, 2018 at 11:19
  • I am having following error TypeError: Type uint32 is not implicitly convertible to expected type int256. how can I resolve it
    – alper
    Commented Nov 24, 2021 at 17:54
9

You can cast from uint to int by just doing int(a-b) but be careful. The int type in solidity uses the two's complement system, so if you accidental cast a very large uint to an int, or a negative int to a uint, you may get unexpected results.

The values where this would happen are extremely large (numbers greater than 2^255, or about 10^77), so you don't usually need to worry, but remember that uint(5-8) is 115792089237316195423570985008687907853269984665640564039457584007913129639933

3

When converting var from int to uint:

if(var < 0) {
    uint(-var);
}
else {
    uint(var);
}

When converting var from uint to int:

if(var >= uint(-1) {
    //can't cast - out of range of int max
}
else {
    int(var);
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.