
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Testing for an Even or Odd Value
|
7
This cast is required because the bitwise operators are overloaded to operate on only
six specific data types:
int, uint, long, ulong, bool, and enumeration data types.
When one of the bitwise operators is used on another data type, that data type is
converted to the supported data type that matches it most closely. Therefore, a
byte
data type is converted to an int before the bitwise complement operator is evaluated:
0x01 // byte y = 1;
0xFFFFFFFE // The value 01h is converted to an int and its
// bitwise complement is taken.
// This bit pattern equals -2 as an int.
0xFE // The resultant int value is cast to its original byte data type.
Notice that the int data type is a signed data type, unlike the byte data type. This is
why you receive
-2 for a result instead of the expected value 254. This conversion of
the byte data type to its nearest equivalent is called numeric promotion. Numeric pro-
motion also comes into play when you use differing data types with binary opera-
tors, including the bitwise binary operators.
Numeric promotion is discussed in detail in the C# Language Specifica-
tion document in section 7.2.6 (this document is available at http://
msdn.microsoft.com/vcsharp/programming/language). It is essential to
understand how numeric promotion ...