Represent int and char in binary format.


An int and char type have the same internal format so we can represent the binary format of an integer or a character value with the same program.The program below uses for(;;) statement (discuss in chapter 2) and a <climits> header’s file .
 

#include < iostream >
#include <çlimits>

using namespace std;

int main()
{
unsigned int i= 97 ;
char c= ‘a’ ;
unsigned int no_of_bitsi=sizeof(int)*CHAR_BIT ; //CHAR_BIT from <climt>
unsigned int no_of_bitsc=sizeof(char)*CHAR_BIT ;

/*Integer in bit format */
for( int is=1 ; is<(no_of_bitsi+1) ; is++ )
{
unsigned int ii=( i >> (no_of_bitsi-is) ) & 1 ;
cout<< ii ;
}
cout<< endl ;
/*Character in bit format */
for( int is=1 ; is<(no_of_bitsc+1) ; is++ )
{
unsigned int ii=( c >> (no_of_bitsc-is) ) & 1 ;
cout<< ii ;
}

cin.get() ;
return 0;
}


 
The binary output will be the same for the value ‘i‘ and ‘c‘, why?.



Related Link

->Float or floating point internal format(IEEE 754 format)(explains why float supports decimal point value while int doesn’t).
 
-> Using wchar_t to print out Japanese,Chinese,Russian in Console.