
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Obtaining the High Word or Low Word of a Number
|
9
Solution
To get the high word of an integer value, perform a bitwise 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.
Discussion
In 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 bit-
wise
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 ...