Get a string input from user, by using unsigned character array. Write a functio
ID: 3810403 • Letter: G
Question
Get a string input from user, by using unsigned character array. Write a function pack() to map the first four characters of the string to an unsigned int variable. Recall that char takes 1 byte, whereas unsigned int is represented in 4 bytes. Print the result unsigned int value. Write another function unpack() which takes in this unsigned int and prints out the four unsigned chars. Sample Output Enter a string [not more than 19 characters]: ICEN_360 String entered = ICEN_360 Result of packing first 4 characters in unsigned int: Value in Base 10 = 1229145422 Value in Binary = 01001001 01000011 01000101 010011 10 Result of unpacking the unsigned int back to char: ICENExplanation / Answer
#include <stdio.h>
//bit representer of an int
void displayInBitFormat(unsigned int character)
{
unsigned int i;//counter
unsigned int displayMask=1<<31;
for (i=1;i<=32;++i)
{
putchar(character&displayMask ? '1':'0');
character<<=1;
if (i%8==0){
putchar(' ');
}
}
putchar(' ');
}
unsigned int packCharacters(unsigned char input[])
{
unsigned int c;
int i = 0;
c = input[0];
for (i = 1; i < 4; i++)
{
c = c << 8;
c = c | input[i];
}
return c;
}
void unpack(unsigned char bytes[], unsigned int n)
{
bytes[0] = (n >> 24) & 0xFF;
bytes[1] = (n >> 16) & 0xFF;
bytes[2] = (n >> 8) & 0xFF;
bytes[3] = n & 0xFF;
}
int main()
{
unsigned char input[20];
printf("Enter a String [not more than 19 characters]: ");
scanf("%s", input);
printf("String entered = %s ", input);
unsigned int c = packCharacters(input);
printf("Result of packing first 4 chacters in unsigned int: ");
printf("Value in Base 10 = %u ", c);
printf("Value in Binary = ");
displayInBitFormat(c);
unsigned char ch[4];
unpack(ch, c);
printf("Result of unpacking the unsigned int back to char: %s ", ch);
return 0;
}
Sample run
Enter a String [not more than 19 characters]: ICEN_360
String entered = ICEN_360
Result of packing first 4 chacters in unsigned int:
Value in Base 10 = 1229145422
Value in Binary = 01001001 01000011 01000101 01001110
Result of unpacking the unsigned int back to char: ICEN
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.