packc.c (1369B)
1 /* Exercise 10.13/14 */ 2 3 #include <stdio.h> 4 5 typedef unsigned u_int; 6 7 void pbits(u_int n); 8 u_int packC(char a, char b); 9 void UnpackC(u_int pack, char *a, char *b); 10 11 int main(void) 12 { 13 char a, b; 14 u_int result; 15 16 /* Take the chars */ 17 printf("two chars: "); 18 scanf("%c%*c%c", &a, &b); 19 20 /* Print the values in bits */ 21 printf("pbits(%d):\t", a); 22 pbits(a); 23 24 putchar('\n'); 25 26 printf("pbits(%d):\t", b); 27 pbits(b); 28 29 putchar('\n'); 30 31 /* Pack the chars and print the values */ 32 result = packC(a, b); 33 34 printf("pbits(%u):\t", result); 35 pbits(result); 36 37 putchar('\n'); 38 39 a = b = '\0'; /* Clean the variables */ 40 41 /* UnPack the chars and print the values */ 42 UnpackC(result, &a, &b); 43 printf("Uncompressed: a[%c] b[%c]\n", a, b); 44 45 return 0; 46 } /* E0F main */ 47 48 /* Print a number in bits */ 49 void pbits(u_int n) 50 { 51 u_int mask = 1 << 31; 52 int i; 53 54 for(i = 1; i <= 32; i++) { 55 printf("%u", n & mask ? 1 : 0); 56 57 if( !(i % 8) ) 58 putchar(' '); 59 60 n <<= 1; 61 } 62 63 } /* eof pbits() */ 64 65 /* Compress two char to an unsigned */ 66 u_int packC(char a, char b) 67 { 68 return (a << 8) | b; 69 } /* eof packC() */ 70 71 /* UnCompress and unsigned to two chars */ 72 void UnpackC(u_int pack, char *a, char *b) 73 { 74 u_int num = pack; 75 76 num &= 65280; 77 *a = num >>= 8; 78 79 num = pack; 80 num &= 255; 81 *b = pack; 82 83 } /* eof UnpackC() */ 84