PART I
C h a p t e r 4 :
O p e r a t o r s
77
PART IPART I
num: 4
num after turning on bit zero: 5
num: 5
num after turning on bit zero: 5
num: 6
num after turning on bit zero: 7
num: 7
num after turning on bit zero: 7
num: 8
num after turning on bit zero: 9
num: 9
num after turning on bit zero: 9
num: 10
num after turning on bit zero: 11
The program works by ORing each number with the value 1, because 1 is the value that
produces a value in binary in which only bit zero is set. When this value is ORed with any
other value, it produces a result in which the low-order bit is set and all other bits remain
unchanged. Thus, a value that is even will be increased by 1, becoming odd.
An exclusive OR, usually abbreviated XOR, will set a bit on if, and only if, the bits being
compared are different, as illustrated here:
0 1 1 1 1 1 1 1
^ 1 0 1 1 1 0 0 1
-------------------------
1 1 0 0 0 1 1 0
The XOR operator has an interesting property that is useful in a variety of situations.
When some value X is XORed with another value Y, and then that result is XORed with Y
again, X is produced. That is, given the sequence
R1 = X ^ Y;
R2 = R1 ^ Y;
R2 is the same value as X. Thus, the outcome of a sequence of two XORs using the same
value produces the original value. This feature of the XOR can be put into action to create
a simple cipher in which some integer is the key that is used to both encode and decode a
message by XORing the characters in that message. To encode, the XOR operation is applied
the first time, yielding the ciphertext. To decode, the XOR is applied a second time, yielding
the plaintext. Of course, such a cipher has no practical value, being trivially easy to break.
It does, however, provide an interesting way to demonstrate the effects of the XOR, as the
following program shows:
// Demonstrate the XOR.
using System;
www.freepdf-books.com
78
P a r t I :
T h e C # L a n g u a g e
class Encode {
static void Main() {
char ch1 = 'H';
char ch2 = 'i';
char ch3 = '!';
int key = 88;
Console.WriteLine("Original message: " + ch1 + ch2 + ch3);
// Encode the message.
ch1 = (char) (ch1 ^ key);
ch2 = (char) (ch2 ^ key);
ch3 = (char) (ch3 ^ key);
Console.WriteLine("Encoded message: " + ch1 + ch2 + ch3);
// Decode the message.
ch1 = (char) (ch1 ^ key);
ch2 = (char) (ch2 ^ key);
ch3 = (char) (ch3 ^ key);
Console.WriteLine("Encoded message: " + ch1 + ch2 + ch3);
}
}
Here is the output:
Original message: Hi!
Encoded message:
❑
1y
Encoded message: Hi!
As you can see, the result of two XORs using the same key produces the decoded message.
(Remember, this simple XOR cipher is not suitable for any real-world, practical use because
it is inherently insecure.)
The unary one’s complement (NOT) operator reverses the state of all the bits of the
operand. For example, if some integer called
Do'stlaringiz bilan baham: |