Help understand whats happening in this function

I need help to understand whats happening in this function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    void trackDeviceIDs(uint8_t source, LibPlatformHardware::CCANNotifier::SCanMsgData& data)
  {
    DSP::Messages  msg = static_cast<DSP::Messages>(data.auiData[0]);
    if (msg==DSP::ModuleID)
    {
      uint64_t modID = 0;
      modID = modID | (uint64_t)(data.auiData[1]) << 32;
      modID = modID | (uint64_t)(data.auiData[2]) << 24;
      modID = modID | (uint64_t)(data.auiData[3]) << 16;
      modID = modID | (uint64_t)(data.auiData[4]) << 8;
      modID = modID | (uint64_t)(data.auiData[5]) << 0;
      if(verbose)  std::cout << "Boom module found @" << std::hex << (int)source << ", ID:" << modID << std::endl;
      devices_seen[modID] = source;
    }
  }


specifically, what is happening here:

1
2
3
4
5
      modID = modID | (uint64_t)(data.auiData[1]) << 32;
      modID = modID | (uint64_t)(data.auiData[2]) << 24;
      modID = modID | (uint64_t)(data.auiData[3]) << 16;
      modID = modID | (uint64_t)(data.auiData[4]) << 8;
      modID = modID | (uint64_t)(data.auiData[5]) << 0;


Be very general, obviously, you would need to see a lot more code to understand it completely. I am just not sure whats happening with the | and the << operators.
Last edited on
It's building a (potentially gigantic) index to use on the devices_seen array. It's building the index by shifting the elements of the data.auidata array (which I'm guessing are unsigned chars) and bitwise-oring them into an unsigned 64 bit value. An example of the same kind of thing:

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <cinttypes>

int main() {
    unsigned char a[5] = {1, 2, 3, 4, 5};
    uint64_t m = (uint64_t)a[0] << 32
               | (uint64_t)a[1] << 24
               | (uint64_t)a[2] << 16
               | (uint64_t)a[3] <<  8
               | (uint64_t)a[4];
    std::cout << std::hex << m << '\n'; // prints 102030405
}

I am not sure I understand what the point would be but I think I understand whats happening. For instance:

modID = modID | (uint64_t)(data.auiData[1]) << 32;

modID starts at 0 and is then set equal to 0 (bitwise-ored) with the first element of data.auiData (casted as uint64_t) which is then shifted by 32. I think shifting it by 32 just means add 32 zeros to the value, right?
Last edited on
yes shifting zero has no effect. shifts multiply or divide by 2 per bit shifted, so 1 shifted twice is 4, or 4 shifted back the other way twice is 1 (divides by 2 2 times)




Registered users can post here. Sign in or register to post.