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.


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

| improve this answer | |
  • 1
    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. – Antti Haapala Mar 24 '18 at 8:06
  • 1
    *casting => conversion – Antti Haapala Mar 24 '18 at 11:19

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

| improve this answer | |

When converting var from int to uint:

if(var < 0) {
else {

When converting var from uint to int:

if(var >= uint(-1) {
    //can't cast - out of range of int max
else {
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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