31 August 2010

Portability tip: How to know the size of primitive data types on your machine

In C the size of primitive data types are machine and compiler dependent.
So, you shouldn't make any assumption when about the max number that int or short or any other primitive data types can hold.

But, by applying the following trick, you can get the max number of bits each primitive type can hold.

/**
* @auther: mhewedy
* @date 31/08/2010
* get_types_bits.c
*/

#include <stdio.h>

int int_bits();
int short_bits();
int long_bits();
int long_long_bits();
int char_bits();

int main(void)
{
printf("%i %i %i %i %i\n",char_bits(), short_bits(), int_bits(), long_bits(), long_long_bits());

return 0;
}

int int_bits()
{
unsigned int x = ~0;
int c=0;

while (x>0)
{
x>>=1;
c++;
}
return c;
}

int short_bits()
{
unsigned short int x = ~0;
int c=0;

while (x>0)
{
x>>=1;
c++;
}
return c;
}

int long_bits()
{
unsigned long int x = ~0;
int c=0;

while (x>0)
{
x>>=1;
c++;
}
return c;
}

int long_long_bits()
{
unsigned long long int x = ~0;
int c=0;

while (x>0)
{
x>>=1;
c++;
}
return c;
}

int char_bits()
{
unsigned char x = ~0;
int c=0;

while (x>0)
{
x>>=1;
c++;
}
return c;
}


Post a Comment