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