Calculate range of data types using C++
C++ program for printing the range data type like int, char, short.
Signed Data Types
METHOD
1.) calculate total number of bits by multiplying sizeof with 8 (say n)
2.) Calculate -2^(n-1) for minimum range
3.) Calculate (2^(n-1))-1 for maximum range
#include <bits/stdc++.h>
#define SIZE(x) sizeof(x) * 8
using namespace std;
void printSignedRange( int count)
{
int min = pow (2, count - 1);
int max = pow (2, count - 1) - 1;
printf ( "%d to %d" , min * (-1), max);
}
int main()
{
cout << "signed char: " ;
printSignedRange(SIZE( char ));
cout << "\nsigned int: " ;
printSignedRange(SIZE( int ));
cout << "\nsigned short int: " ;
printSignedRange(SIZE( short int ));
return 0;
}
|
Output:
signed char: -128 to 127
signed int: -2147483648 to 2147483647
signed short int: -32768 to 32767
Unsigned Data Types
METHOD
1.)Find number of bits by multiplying result of sizeof with 8 say n
2.)minimum range is always zero for unsigned data type
3.)for maximum range calculate 2^n-1
#include <bits/stdc++.h>
#define SIZE(x) sizeof(x) * 8
using namespace std;
void UnsignedRange( int count)
{
unsigned int max = pow (2, count) - 1;
cout << "0 to " << max;
}
int main()
{
cout << "unsigned char: " ;
UnsignedRange(SIZE(unsigned char ));
cout << "\nunsigned int: " ;
UnsignedRange(SIZE(unsigned int ));
cout << "\nunsigned short int: " ;
UnsignedRange(SIZE(unsigned short ));
return 0;
}
|
Output:
unsigned char: 0 to 255
unsigned int: 0 to 4294967295
unsigned short int: 0 to 65535
Last Updated :
12 Jan, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...