stackoverflow1453

Programming&&Games&&Life

Archive for November, 2013

Write a program that inputs two characters from the keyboard and passes them to function packCharacters which pack two character values into an unsigned integer variable.

/*

Name:
Copyright: Deitel C How to Program
Author: StackOverflow1453
Date: 10/31/2013 2:26:49 PM
Description:

The left-shift operator can be used to pack two character values into an unsigned integer variable. Write a program that
inputs two characters from the keyboard and passes them to function packCharacters. To pack two characters into an unsigned
integer variable, assign the first character to the unsigned variable, shift the unsigned variable left by 8 bit positions and combine
the unsigned variable with the second character using the bitwise inclusive OR operator. The program should output the characters
in their bit format before and after they are packed into the unsigned integer to prove that the characters are in fact packed correctly
in the unsigned variable.

Example Output:

Enter two characters: A B
'A' in bits as an unsigned integers is:
65 =	00000000 01000001
'B' in bits as an unsigned integers is:
66 =	00000000 01000010
'A' and 'B' packed in an unsigned integer:
16706 = 01000001 01000010

*/
#include <stdio.h>
void displayInBitFormat(int);
void packCharacters(int, int );
int i, a, b, pack;

int main(void){

	puts("Enter an integer");
	scanf("%d",&a);

	printf("\n%d's bit representation is: \n",a);
	displayInBitFormat(a);

	puts("Enter an integer");
	scanf("%d",&b);

	printf("\n%d's bit representation is: \n",b);
	displayInBitFormat(b);

	puts("");

	packCharacters(a,b);

	getch();

}

void packCharacters(int m, int n){

	unsigned c=0<<31;

	c=c|n;

	m=m<<16;
	c=c|m;

	printf("Result in binary is: \n");
	displayInBitFormat(c);
	puts("\nResult in decimal number is: ");
	printf("%u", c);

}

//bit representer of an int
void displayInBitFormat(int val){

	int mask=1<<31;

	for (i = 0; i < 32; i++)
	{
		//here inclusive OR checked
		if (val&mask)
		{
			printf("1");

		}
		else
		{
			printf("0");
		}

		if ((i+1)%8==0)
		{
			printf(" ");
		}

		//here val's bits are shifted to left one by one
		val=val<<1;
	}

}