I have written a code to pack two characters to an integer; which should output in both decimal and binary formats.
The code compiled successfully, but the problem is,
One other possible approach using getchar()
is to manually eat the \n
with another call to getchar()
. Also, your displayInBitFormat
needs to take a wider type than char
if you are going to use it to print the combined expression.
#include
#include
void displayInBitFormat(unsigned int character);
void packCharacters(char character1, char character2 );
int character1, character2;
int main(void){
puts("Enter the first character");
character1 = getchar();
// Eat the newline that came from reading the first character.
getchar();
printf("\n%c's bit representation is: \n",character1);
displayInBitFormat(character1);
printf("Enter the second character");
character2 = getchar();
printf("\n%c's bit representation is: \n",character2);
displayInBitFormat(character2);
puts("");
packCharacters(character1,character2);
}
void packCharacters(char character1, char character2){
unsigned int c;
c=character1; // assigning first character with unsigned
c=c<<8; // shifting first char to 8 bits left
c=c|character2; //bitwise inclusive OR
printf("After packing characters, Result in binary is: \n");
displayInBitFormat(c);
puts("\nResult in decimal number is: ");
printf("%u\n", c);
}
//bit representer of an int
void displayInBitFormat(unsigned int character){
unsigned int i;//counter
unsigned int displayMask=1<<31;
printf("%10u=",character);
for (i=1;i<=32;++i)
{
putchar(character&displayMask ? '1':'0');
character<<=1;
if (i%8==0){
putchar(' ');
}
}
putchar('\n');
}