3.3 – Integer types in C language Part-1

by subbu on August 29, 2013

Integer types in C language

C language has 4 integer types to store integer numbers. The difference among these types is the bytes of memory each type selects in the memory. Smaller the size stores smaller integers and larger the size stores larger integers.

Say for example if an integer type takes 1byte (8bits) then the maximum number that it can hold is 1111 1111 or 28-1 (255). In the same way if an integer type takes 2bytes (16bits) then the maximum number that it can hold is 1111 1111 1111 1111 or 216-1 (65535). Following are the integer types available in C language

char 1byte 8bits
short 2bytes 16bits
int 2bytes or 4bytes 16bits or 32bits
long 4bytes 32bits

Though char is an integer type we will discourse it in another session.

In some compilers short, int, short int are treated as same type, takes just 2 bytes. In some other compilers short and int are treated as separate types, where short takes 2bytes and int takes 4bytes.

We can test the compiler behavior using sizeof() operator as explained in the previous session.

In the following tutorial let us typically assume

  • char takes 1 byte
  • short or int or short int takes 2bytes
  • long or long int takes 4 bytes

How a positive value is stored in integer types:

When a positive integer is assigned to any integer type of memory allocation then the first or higher most bit is used to store the sign that is 0 for positive and remaining bits are used to store the actual value. Say for example an int type takes 2bytes or 16bits of memory, out of which the first bit is used to store the sign (0) and remaining 15bits are used to store the actual value. Hence the maximum limit of int type is 111 1111 1111 1111 (215-1 or 32767).

int num=379;

How a positive integer is stored

How a positive integer is printed by the printf():

While printing, the printf() first look at the first bit, if it is a zero then understands that it is a positive number and prints decimal equal to remaining 15 bits binary value.

#include<stdio.h>
int main()
{
int num=379;
printf("%d",num);
return 0;
}

Output:
379

How printf() prints positive integer

How a negative value is stored in integer types:

When we assign a negative value to an integer type of memory allocation then its 2’s compliment of binary is stored in the memory. Here the 1’s compliment is making 0s as 1s and 1s as 0s and the 2’s compliment is adding 1 to the 1’s compliment.

int num=-379;

assigning negative integer

How a negative integer is printed by the printf():

While printing, the printf() first look at the first bit, if it is 1 then understands that it is a negative number and reverts the 2’s and 1’s compliments. Finally prints the decimal equal of resultant binary number with -ve sign.

#include<stdio.h>
int main()
{
int num=-379;
printf("%d",num);
return 0;
}

Output:
-379

printing negative integer

Previous post:

Next post: