| | | | un(1100 0011 0101 0000) = 50000 si(1100 0011 0101 0000) = -15536 | | | | | | The point to keep in mind is that we are actually passing or receiving a binary word, not a number. VB and Win32 will both interpret this binary word as a number. The difficulty comes when they use different interpretations. VB uses the signed integer interpretation, and Win32 (we are assuming) uses the unsigned short integer interpretation. | | | | | | Thus, referring to Figure 5-1, in passing a number un(w) to an API function, we need to tell VB to pass the number si(w), since Win32 will interpret the binary word w that is actually passed (on the stack) as un(w). Conversely, in receiving a number, VB will see it as si(w), and we need to make the translation to si(w) which, by the way, will require using a larger VB data type to hold the value. | | | | | | So the whole problem boils down to translating between si(w) and un(w). | | | | | | We can see how to make these translations by noting that the only difference between Table 5-1 and Table 5-3 is the negative sign in the first column. Accordingly, there are two cases to consider. | | | | | | The first case is when the number si(w) is nonnegative or, equivalently, the number un(w) is in the lower half of the unsigned range (0 to 32767). (Whether we are passing or receiving, we will know one of these numbers!) In this case, the sign bit of w is 0. Hence, as we have seen: | | | | | | un(w) = si(w) | | | | | | Thus, in this case, we can use an ordinary VB integer to pass the number, and, in the other direction, the return value in a VB integer is the actual number (no changes are necessary). | | | | | | On the other hand, suppose that the number si(w) is negative or, equivalently, un(w) is in the upper range 32768 to 65535. In this case, the sign bit of w is 1. This bit, being in the first column of Table 5-4, contributes a total of 215 to the number un(w). On the other hand, it contributes a total of -215 to the number si(w). Since the contributions from all other columns are the same in both un(w) and si(w), subtracting out the contributions from the first column should produce equal values, that is: | | | | | | un(w) - 2^15 = si(w) - (-2^15) | | | | | | From this, a little algebra gives the two formulas: | | | | | | un(w) = si(w) + 2^16 si(w) = un(w) - 2^16 | | | | | | These formulas are the key to all. We can now summarize. | | |