Solution for Exercise 17-9
ex1709
#include <stdio.h> char *binbin(unsigned char n); int main() { int a,x,r; a = 73; x = 170; printf(" %s %3d\n", binbin((unsigned char)a),a); printf("^ %s %3d\n", binbin((unsigned char)x),x); r = a ^ x; printf("= %s %3d\n", binbin((unsigned char)r),r); printf("^ %s %3d\n", binbin((unsigned char)x),x); a = r ^ x; printf("= %s %3d\n", binbin((unsigned char)a),a); return(0); } char *binbin(unsigned char n) { static char bin[9]; int x; for(x=0;x<8;x++) { bin[x] = n & 0x80 ? '1' : '0'; n <<= 1; } bin[x] = '\0'; return(bin); }
Output
01001001 73
^ 10101010 170
= 11100011 227
^ 10101010 170
= 01001001 73
Notes
* In Line 21 I'm re-using the a
variable to avoid having to declare another variable simply to hold the result of the XOR operator. Even so, due to XOR's charm, the value that ends up in variable a
is the same value it began with, 73.
* The XOR operator can be used as a quick and dirty cipher. The code is easy to break, so it's by no means secure, but the ^
operator can be used to swiftly encrypt and decrypt text. You can try coding such a program on your own; click here for my example.
Copyright © 1997-2024 by QPBC.
All rights reserved