-3

I want to find out if a number is odd or not. I want to compare the LSB and not use modulo.

int main(int argc, char*argv[])
{
    if ( argc >1 ) {
        if ( atoi(argv[1]) & 0x1 == 1 ) 
            printf ("odd num \n");
    }
    return 0;
}


# ./odd 2
# ./odd 3
odd num 
# ./odd 22
# ./odd 23
# ./odd 33
odd num 
# ./odd 43
# ./odd 52
odd num 
# file odd
odd: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.24, BuildID[sha1]=0x56f7eb1e7a35762bd8b786eefb5516a14549fc1f, not stripped
resultsway
  • 12,299
  • 7
  • 36
  • 43
  • 7
    That's not how you convert a string into an integer. – cnicutar Jan 16 '13 at 19:46
  • 1
    Possible duplicate: [What is the fastest way to find if a number is even or odd?](http://stackoverflow.com/questions/2229107/what-is-the-fastest-way-to-find-if-a-number-is-even-or-odd) – Kim Hansson Jan 16 '13 at 19:48
  • @StephenCanon The brain should be the first choice. If that is insufficient, switch to the debugger. – ott-- Jan 16 '13 at 19:53

1 Answers1

5

You are confusing numbers with representations of numbers. The input to this program is a representation of a number like "22" (the decimal digit "2" repeated twice), not a number like twenty two (the one that comes after twenty one). Telling the compiler to pretend it's a number won't work.

   if ( *(unsigned int*)argv[1] & 0x1 == 1 )

Since argv[1] is a pointer to a string, telling the compiler to pretend it's a pointer to an unsigned integer will give you garbage.

Your probably want atoi(argv[1]), which converts a string that represents a number in decimal form into the number it represents.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278