Recipe 1.6. Obtaining the High Word or Low Word of a NumberProblemYou have a 32-bit integer value that contains information in both its lower and upper 16 bits. You need methods to get the high word (first 16 bits) and/or the low word (last 16 bits) of this value. SolutionTo get the high word of an integer value, perform a bit-wise AND between it and the value, as shown in the following method: public static int GetHighWord(int intValue) { return (intValue & (0xFFFF << 16)); } To get the low word of a value, use the following method: public static int GetLowWord(int intValue) { return (intValue & 0x0000FFFF); } This technique can easily be modified to work with other sizes of integers (e.g., 8-bit, 16-bit, or 64-bit); this trick is shown in the Discussion section. DiscussionIn order to determine the values of the high word of a number, use the following bit-wise AND operation: uint intValue = Int32.MaxValue; uint MSB = intValue & (0xFFFF << 16); // MSB == 0xFFFF0000 This method simply ANDs the number to another number with all of the high word set to 1. This method will zero out all of the low word, leaving the high word intact. In order to determine the values of the low word of a number, use the following bitwise AND operation: uint intValue = Int32.MaxValue; uint LSB = intValue & 0x0000FFFF; // LSB == 0x0000FFFF This method simply ANDs the number to another number with all of the low word set to 1, which zeros out all of the high word, leaving the low word intact. The methods presented here accept only 32-bit integer values. To allow this method to accept other numeric data types, you can simply overload this method to accept any other data types that you require. For example, if you need to also acquire the low or high byte of a 16-bit integer, you can use the same structure as the GetHighWord method as follows: public static short GetHighByte(short shortValue) { return (short)(shortValue & (0xFF << 8)); } The GetLowWord method is modified as shown here: public static short GetLowByte(short shortValue) { return (short)(shortValue & (short)0xFF); } |