Solution for Exercise 17-9
ex1709
#include <stdio.h> char *binbin(int n); int main() { int a,x,r; a = 73; x = 170; printf(" %s %3d\n",binbin(a),a); printf("^ %s %3d\n",binbin(x),x); r = a ^ x; printf("= %s %3d\n",binbin(r),r); printf("^ %s %3d\n",binbin(x),x); a = r ^ x; printf("= %s %3d\n",binbin(a),a); return(0); } char *binbin(int 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); }
Notes
* In Line 17 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