Tuesday, May 19, 2015

AaA

Every language has data types, These will be stored into bits . 

Depending on language design and complier we have size of data types.

Ex : with turbo C , borland c : which are 16 bit complier                :  for 32 bit compiler 

          we have int,float,long as 2 bytes : 16 bits                         only int size changes to 4 bytes or 32 bits
                       char as 1 byte : 8 bit
                       float,long int : 32 bits 
                       double as 8 bytes : 64 bits 
                        short int as 2 byte : 16 bits 


Further for each compiler we can use sizeof(datatype) function to find out the size of each data type

Now why are we checking all this ??

     In real life , we need new data types which will be needed for different types , therefore we have in C/C++

typedef to define new data types 
and padding which helps in bits full use.


ex : there is no data type which has 24 bits . So we will define  

typedef struct 3byte {  char[3] a;}

Now if we do sizeof of this struct , we will get size as 3 bytes. 

But we do size of below structure

typedef structure mix{

int a; 
char b;
}

the answer wud be 8 and not 5.

This is because of structure alignment. Structure alignment refers to the ability of the compiler to insert unused memory into a structure so that data members are optimally aligned for better performance. Many processors perform best when fundamental data types are stored at byte-addresses that are multiples of their sizes.

So a 16 bit processor has a address of 16 bit , and 32 bit processor a address size of 32 bits.

Also note that every compiler will have different way of structure alignment. 


Now we will see how we can squeeze datatype to their correct size in various complier.

GCC and MS visual Studio

     we can use the #pragma pack(N)  where N tells the packed size now .

     example for below structure 

typedef struct mix{
int a;
char b;
};

if we use #pragma pack(1)  the struct size wud be 5,  if we use #pragma(4) then 8

See the attached file for more understanding


See the another menthod for packing individual structures 

No comments:

Post a Comment