Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is MAKEWORD used for?

Tags:

c++

winapi

I have come across this macro MAKEWORD(2,2) in a piece of instructional code. I read in MSDN that it "Creates a WORD value by concatenating the specified values."

The question is, isn't a WORD something like an unsigned integer why would I ever need to do such a strange procedure such as using MAKEWORD()?

like image 470
user3704920 Avatar asked Jun 10 '14 02:06

user3704920


2 Answers

The macro expects two bytes as its parameters:

WORD MAKEWORD(
  BYTE bLow,
  BYTE bHigh
);

Its defined in Windef.h as :

#define MAKEWORD(a,b)   ((WORD)(((BYTE)(a))|(((WORD)((BYTE)(b)))<<8)))

It basically builds a 16 bits words from two 1 bytes word (and doesn't look very portable)

The binary representation of the number 2 with 1 byte (a WORD) is : | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 |

If we take the concatenate two of those bytes as in MAKEWORD(2,2) , we get:

| 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 |

Which is 512 + 2 = 514 : live demo.

The only real life example of this particular macro is in the Initialization of Winsock, to generate the versioning word expected by WSAStartup.

like image 126
quantdev Avatar answered Sep 18 '22 03:09

quantdev


Roughly speaking, MAKEWORD(x,y) is equivalent to ((y) << 8 | (x)); this is useful when packing two byte-sized values into a single 16-bit field, as often happens with general-purpose message structures. The complementary operation is performed by the LOBYTE and HIBYTE macros, which extracts the low- or high-order byte from a WORD operand.

The macro saw considerable use during the 16-bit days of Windows, but its importance declined once 32-bit programs came to dominance. Another vestige of 16-bit Windows lies in the names of the MSG structure members wParam and lParam, which were originally typed WORD and LONG respectively; they're both LONG now.

Trememdous historical insight can be found in Charles Petzold's tome, Programming Windows, second edition.

like image 34
Jeffrey Hantin Avatar answered Sep 20 '22 03:09

Jeffrey Hantin