[Win32 API, C] Bit shifting

  • #1
Silicon Waffle
162
203
In Win32 API, I see the define macro MAKEWORD
#define MAKEWORD( h, l ) \
( ( ( WORD )( h ) << 8 ) | ( BYTE )( l ) )

Why does it make a shift of 8 bits ?

In C#, they have a BitConverter.ToInt32, which performs something similar to this Makeword and I use this 8 bit shift and it works correctly. But they also have ToInt16 which shifting like this works correctly too in some of my cases. I'm so confused about 32 and 16 in this case.
That is, at some places where I change makeword to make a shift of 16, it works correctly whereas at others where shifting 16 is required, the output then becomes incorrect since shifting 8 is more precise.

It looks like casting is the issue but how
PHP:
int MAKEWORD(const int*& val, const int& index)
{ 
   return (int)(((int)(val[index + 1]) << 16) + (short)(val[index]));
}
 
Last edited:

Answers and Replies

  • #2
ScottSalley
21
10
The Win32API MAKEWORD is from a long time ago when Windows applications were 16-bit so a 'WORD' was a 16-bit integer (which would be considered a 'short' with modern compilers). It is taking two bytes (each 8 bits), a 'high' byte ('h') and a low byte ('l'), and shifting them into the proper places to make a 16-bit integer.

The ToInt32 function takes an array and an index and coverts the 4 bytes located from the index into a 32-bit integer. Useful for deserializing information from disk or a network.

I'm not sure what your function MAKEWORD is trying to do (and I'm not familiar with C#), but looks wrong to me because:
1. Your input 'val' is an array of integers. I think that it should be either an array of bytes or shorts.
2. You cast val[index+1] to an int but val[index] to a short.

If your goal was to make something like the MAKEWORD from Win32 API that works on byte arrays:
short MAKEWORD(const byte*& val, const int& index)
{
return ((short)val[index + 1]) << 8 + (short)(val[index]); // WARNING: I don't know C#
}
 

Suggested for: [Win32 API, C] Bit shifting

Replies
4
Views
328
Replies
13
Views
602
  • Last Post
Replies
13
Views
750
Replies
49
Views
2K
Replies
1
Views
309
Top