/* --------------------------------------------------------------------- ** Figure 18.16: Decrypting a number. ** --------------------------------------------------------------------- */ #include "tools.h" #define AD 0x0E00 /* bits 4:6 goto 0:2 */ #define BD 0x001F /* bits 11:15 goto 3:7 */ #define CD 0xF000 /* bits 0:3 goto 8:11 */ #define DD 0x01E0 /* bits 7:10 goto 12:15 */ unsigned short decrypt( unsigned short n ); void main( void ) { unsigned short in; short dcrypt; printf( "Enter an encrypted short int: " ); scanf( "%hu", &in ); dcrypt = (signed) decrypt( in ); printf( "\n The encrypted input number in base 10 is: %hu \n" "Encrypted input number in hexadecimal is: %hx \n\n" "The decrypted number in base 10 is: %hi \n" "The decrypted number in base 16 is: %hx \n\n", in, in, dcrypt, dcrypt ); } /* ----------------------------------------------------------------------- */ unsigned short /* use unsigned for bit manipulation */ decrypt( unsigned short n ) { unsigned short a, b, c, d; /* for the four parts of n */ a = (n & AD) << 4; /* Isolate bits 4:6, shift to positions 0:2. */ b = (n & BD) << 8; /* Isolate bits 11:15, shift to positions 3:7. */ c = (n & CD) >> 8; /* Isolate bits 0:3 shift to positions 8:11,. */ d = (n & DD) >> 5; /* Isolate bits 7:10, shift to positions 12:15. */ return a | b | c | d; /* Pack the four parts back together. */ }