Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LOWORD and HIWORD operations

I've come into contact with some weird notation in a C++ program. I'm dealing with bit shifting and I came across the LOWORD() and HIWORD() functions. I understand that LOWORD is the value of the lower 2 bytes of an integer. I also know that HIWORD is the higher 2 byes of that integer. However, I came into contact with a code snippet which looked something like this:

#define LOWORD(l)           ((WORD)(((DWORD_PTR)(l)) & 0xffff))
#define HIWORD(l)           ((WORD)((((DWORD_PTR)(l)) >> 16) & 0xffff))

int v1 = 0x12343460;
int v2 = 0x11111111;
HIWORD(v2) = HIWORD(v1);
LOWORD(v1) = LOWORD(v2);

From what it appears, it looks as though the programmer is suggesting to place the value of one function into another function. However, that seems impossible without some serious programmer magic. Any help whatsoever in decrypting this code snippet would be greatly appreciated.

like image 662
Sean Avatar asked Sep 17 '25 14:09

Sean


1 Answers

Wow, that is truly hideous code. About the only way I could see that working (as functions) is if the functions returned references to the parts of the variables passed in. In other words, something like:

#include <iostream>

unsigned short int & HIWORD(unsigned int & x) {
    return *(reinterpret_cast<unsigned short int *>(&x) + 1);
}

unsigned short int & LOWORD(unsigned int & x) {
    return *(reinterpret_cast<unsigned short int *>(&x) + 0);
}

int main() {
    unsigned int v1 = 0x11112222;
    unsigned int v2 = 0x33334444;

    std::cout << "Before: " << std::hex << v1 << ' '  << v2 << '\n';

    HIWORD(v2) = HIWORD(v1);
    LOWORD(v1) = LOWORD(v2);

    std::cout << "After : " << std::hex << v1 << ' '  << v2 << '\n';
}

This (at least on my system) generates what you're probably seeing:

Before: 11112222 33334444
After : 11114444 11114444

But, if you actually see code like that, I'd suggest one of two courses of action:

  1. Fix it. There are about a hundred better ways you could do the same thing.
  2. Leave. Just leave. Don't collect your belongings. Just get up from your chair, walk out the door, get in your car, drive off and never come back :-)

Now it's possible they may be macros rather than functions but my advice still stands regarding the two possible options.

like image 121
paxdiablo Avatar answered Sep 20 '25 06:09

paxdiablo