Search code examples
cintbitunsigned-integer

Calculate how much bits is in int without sizeof()


i am trying to create simple game. Task is to create program that calculate size of int in bites. Their code is

#include <stdio.h>
int intSize(void)
{
    unsigned int x,
        i = 0;
        x = ?;
    while ((?) != 0)
        ?;
    return ?;
}
int main()
{
    printf("Size is %d bits\n",?);
    return 0;
}

? is place where i should put my code.

This is what one of my tries

#include <stdio.h>
int intSize(void)
{
    unsigned int x,
        i = 0;
        x = 0;
    while ((x>>1) != 0)
        i++;
    return i;
}
int main()
{
    printf("Size ise %d bits\n", intSize());
    return 0;
}

I know that usigned int is 4bytes so i use bitwise operation to move bits it should be 32 but i am getting 1. I will be thankfull for any help.


Solution

  • Having

    x = 0;
    while ((x>>1) != 0)
      ...
    

    the while stops immediately, so i is unchanged and the return value is 0.

    The right way was to initialize x with~0u to have all bits valuing 1 (suppose 2-complements)

    Out of that the test is not the right one and you missed to modify the value of x.

    In

    printf("Size ise %d bits\n", intSize);
    

    you missed the () to call the function, currently you try to write its address, I say try because an address must be printf with the format %p.

    Finally:

    #include <stdio.h>
    
    int intSize(void)
    {
      unsigned int x,
         i = 0;
    
      x = ~0u;
      while ((x & 1) != 0)
        (i+= 1, x /= 2); /* not x >= 1 in case it is a rotate rather than a shift */
      return (int) i;
    }
    
    int main()
    {
        printf("Size is %d bits\n", intSize());
        return 0;
    }
    

    Compilation and execution:

    pi@raspberrypi:/tmp $ gcc -Wall s.c
    pi@raspberrypi:/tmp $ ./a.out
    Size is 32 bits
    pi@raspberrypi:/tmp $ 
    

    So in order the '?' are :

    • ~0u
    • x & 1
    • (i+= 1, x /= 2)
    • (int) i