( C programming only) The left-shift operator can be used to pack four character
ID: 3806276 • Letter: #
Question
(C programming only) The left-shift operator can be used to pack four character values into a four-byte unsigned integer variable. Write a program that inputs four characters from the keyboard and passes them to function packCharacters. To pack four characters into an unsigned integer variable, assign the first character to the unsigned variable, shift the unsigned integer variable left by 8 bit positions and combine the unsigned variable with the second character using the bitwise inclusive OR operator. Repeat this process for the third and fourth characters. 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.
Desired output:
Enter the first character :K
Enter the second character :L
Enter the third character :M
Enter the fourth character :N
Result after replacing last 8 bits with K
75 = 00000000 00000000 00000000 01001011
Result after shifting 8 bits to the left
19200 = 00000000 00000000 01001011 00000000
Result after replacing last 8 bits with L
19276 = 00000000 00000000 01001011 01001100
Result after shifting 8 bits to the left
4934656 = 00000000 01001011 01001100 00000000
Result after replacing last 8 bits with M
4934733 = 00000000 01001011 01001100 01001101
Result after shifting 8 bits to the left
1263291648 = 01001011 01001100 01001101 00000000
Result after replacing last 8 bits with N
1263291726 = 01001011 01001100 01001101 01001110
Result after shifting 8 bits to the left
1280134656 = 01001100 01001101 01001110 00000000
Explanation / Answer
#include <stdio.h>
#define INT_SIZE sizeof(int) * 8 //Size of int in bits
int main()
{
int num, index, i;
int bin[INT_SIZE];
printf("Enter any number: ");
scanf("%d", &num);
index = INT_SIZE;
while(index!=0)
{
index--;
//Store 1 if LSB is set otherwise 0
bin[index] = num & 1;
//Shift bits of num to one position right
num >>= 1;
}
printf("Converted binary (in %d byte integer representation): ", sizeof(int));
for(i=0; i<INT_SIZE; i++)
{
printf("%d", bin[i]);
}
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.