1
I’m having difficulty in the following exercise
Using the right shift operator, the AND operator over bits and a mask, write a function called unzippaCaracters that receives the integer unsigned and unpack in two characters from an unsigned integer, match the unsigned integer with the 65280 mask (00000000 00000000 11111111111 00000000) and move the result in bits to the right. Assign the resulting value to a variable char. Then combine the unsigned integer with the mask 255 (00000000 00000000 00000000 11111111111). Assign the result to another char variable. The program must print the unsigned integer in bits before it is unzipped and then print the characters in bits to confirm that they have been unzipped correctly. :
The first character I can unzip, but the second character does not get the correct value (it is the same value as the first character unzipped).
Below I put the functions I am using to try to solve the exercise
#include <stdio.h>
#include <stdlib.h>
void compactaCaracteres(char a,char b);
void descompactaCaracteres(unsigned valor);
void mostrarBits(unsigned valor);
int main(void){
char var1,var2;
printf("Digite um caractere:");
scanf("%c",&var1);
setbuf(stdin,NULL);
printf("Digite um caractere:");
scanf("%c",&var2);
compactaCaracteres(var1,var2);
return 0;
}
void compactaCaracteres(char a,char b){
unsigned compacta = a;
compacta <<= 8;
compacta |= b;
descompactaCaracteres(compacta);
}
void descompactaCaracteres(unsigned valor){
mostrarBits(valor);
valor &= 65280;
valor >>= 8;
char a = valor;
mostrarBits(a);
char b = valor & 255;
mostrarBits(b);
}
// Função utilizada para imprimir os bits
void mostrarBits(unsigned valor){
unsigned contador;
unsigned mascara = 1 << 31;
printf("%10u = ",valor);
for(contador = 1 ; contador <= 32; contador++){
putchar(valor & mascara ? '1' : '0');
valor <<= 1;
if(contador % 8 == 0){
putchar(' ');
}
}
putchar('\n');
}