Integer and the no. of bits it occupy

This is a discussion on Integer and the no. of bits it occupy within the C Programming forums, part of the General Programming Boards category; I"m beginning to learn C .The book I follow tells that when any variable has been declared as type int ...

  1. #1
    Registered User
    Join Date
    Dec 2005
    Posts
    25

    Integer and the no. of bits it occupy

    I"m beginning to learn C .The book I follow tells that when any variable has been declared as type int , in 32 bit computer the maximum integer that can be stored is 2147483647 while on 16
    bit it is 32767.I'd initialized a variable to 32768 which I could print ,however when I tried to print 2147483647 it gave -1(while I tried to print it on to the screen). So could any one tell me how many bits my compute uses?

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    Ask your system:
    Code:
    #include <stdio.h>
    #include <limits.h>
    
    int main(void)
    {
       printf("INT_MAX = %d\n", INT_MAX);
       printf("INT_MIN = %d\n", INT_MIN);
       return 0;
    }
    [edit]
    Code:
    #include <stdio.h>
    #include <limits.h>
    
    int main(void)
    {
       printf("CHAR_BIT = %d\n", CHAR_BIT);
       printf("sizeof(int) = %d\n", (int)sizeof(int));
       printf("An int occupies %d bits.\n", (int)(CHAR_BIT * sizeof(int)));
       return 0;
    }
    
    /* my output
    CHAR_BIT = 8
    sizeof(int) = 4
    An int occupies 32 bits.
    */
    Last edited by Dave_Sinkula; 12-15-2005 at 09:04 AM.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    Sr. Software Engineer filker0's Avatar
    Join Date
    Sep 2005
    Location
    West Virginia
    Posts
    235
    Or, alternatively:
    Code:
    #include <stdio.h>
    
    int main(void)
    {
        printf("There are %d bits in an int on this machine\n", sizeof(int) * 8);
        return 0;
    }
    This will give you a direct result for any modern machine where there are 8 bits per smallest addressable memory unit larger than a single bit, which is usually a byte.

    [edit]It looks as though I was beaten to the punch, and Dave even accounts for different sizes of char. Well done, Dave![/edit]
    Last edited by filker0; 12-15-2005 at 09:09 AM. Reason: Beaten to the punch
    Insert obnoxious but pithy remark here

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21