/* --------------------------------------------------------------------- ** Figure 18.16: Encrypting a number. ** --------------------------------------------------------------------- */ #include "tools.h" #define AE 0xE000 /* bits 0:2 end up as 4:6 */ #define BE 0x1F00 /* bits 3:7 end up as 11:15 */ #define CE 0x00F0 /* bits 8:11 end up as 0:3 */ #define DE 0x000F /* bits 12:15 end up as 7:10 */ unsigned short encrypt( unsigned short n ); void main( void ) { short in; unsigned short crypt; printf( "Enter a short number to encrypt: " ); scanf( "%hi", &in ); /* Cast the int to unsigned before calling encrypt. */ crypt = encrypt( (unsigned short) in ); printf( "\n The input number in base 10 is: %hi \n" " The input number in hexadecimal is: %hx \n\n" " The encrypted number in base 10 is: %hu \n" " The encrypted number in base 16 is: %hx \n\n", in, in, crypt, crypt ); } /* --------------------------------------------------------------------- */ unsigned short /* use unsigned for bit manipulation */ encrypt( unsigned short n ) { unsigned short a, b, c, d; /* for the four parts of n */ a = (n & AE) >> 4; /* Isolate bits 0:2, shift to positions 4:6. */ b = (n & BE) >> 8; /* Isolate bits 3:7, shift to positions 11:15. */ c = (n & CE) << 8; /* Isolate bits 8:11, shift to positions 0:3. */ d = (n & DE) << 5; /* Isolate bits 12:15, shift to positions 7:10. */ return c | a | d | b; /* Pack the four parts back together. */ }