Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

[Win32 API, C] Bit shifting

  1. Dec 24, 2014 #1
    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: Dec 24, 2014
  2. jcsd
  3. Dec 29, 2014 #2
    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#
    }
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: [Win32 API, C] Bit shifting
  1. C++ bit arrays (Replies: 4)

Loading...