Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if unsigned is less than zero

Tags:

c

Playing with some sources found code like this:

void foo(unsigned int i)
{
 if(i<0)
     printf("Less then zero\n");
 else
     printf("greater or equ\n");
}

int main()
{
    int bar = -2;
    foo(bar);
    return 0;
}

I think there is no sense, but may be there some cases(security?) that makes this check sensable?

like image 499
dtoch Avatar asked Jun 21 '12 14:06

dtoch


People also ask

How do you know if unsigned negative?

An unsigned integer can never hold a negative value. If the value of i is negative, then it will be converted to some positive value when you assign it to j . If you want to know whether the value of i is negative, you should test i , not j .

Can you be unsigned negative?

An unsigned is an integer that can never be negative. If you take an unsigned 0 and subtract 1 from it, the result wraps around, leaving a very large number (2^32-1 with the typical 32-bit integer size).

Can Unsign int be less than 0?

An unsigned int cannot be less than 0 by definition. So, to more directly answer your question, you're right in thinking that this makes no sense.

Is zero unsigned or signed?

Zero (0) is also unsigned number. This representation has only one zero (0), which is always positive. Every number in unsigned number representation has only one unique binary equivalent form, so this is unambiguous representation technique.


2 Answers

An unsigned int cannot be less than 0 by definition. So, to more directly answer your question, you're right in thinking that this makes no sense. It is not a meaningful security item either unless you encounter something like a loop that accidently decrements a signed int past 0 and then casts it as an unsigned int for use as an index into an array and therefore indexes memory outside of the array.

like image 64
erapert Avatar answered Oct 16 '22 07:10

erapert


i will always be >=0because it is declared as unsigned and thus interpreted as an unsigned integer. So your first test will always be false.

Your call foo(bar) actually converts an int into an unsigned int. This may be what confuses you. And "conversion" does not actually change the bytes/bits value of your integer, it is just a matter of formal typing and interpretation.

See this answer for examples of signed/unsigned conversions.

Here is a simple example (the exact output depends on the number of bytes of an unsigned inton your system, for me it is 4 bytes).

Code:

printf("%u\n", (unsigned int) -2);

Output:

4294967294
like image 37
wap26 Avatar answered Oct 16 '22 07:10

wap26