[SOLVED] how can I go about doing this... (soln: use reinterpret_cast)

So I have in my library the following struct define:

typedef struct
{
  uint16_t id;
  struct {
    int8_t rtr : 1;
    uint8_t length : 4;
  } header;
  uint8_t data[8];
} tCAN;

In this particular project, I need to manipulate 'data' as a whole number so I though of doing the following which I had tested on jdoodle C compiler (the uint_t's where replace with char/long there! :wink: ):

uint64_t *concat_data;
concat_msg = msg.data;

it compiles and outputs (with a warning) on jdoodle but comes with the following error in IDE:

cannot convert 'uint8_t [8] {aka unsigned char [8]}' to 'uint64_t* {aka long long unsigned int*}' in assignment

one other option (without modifying the library itself) would be to "shift in the bits" i guess but the pointer way is so much neater! :slight_smile:

is there a way to use pointers here?

here's the code I tested (with error):

typedef struct
{
  uint16_t id;
  struct {
    int8_t rtr : 1;
    uint8_t length : 4;
  } header;
  uint8_t data[8];
} tCAN;

void setup() {
  tCAN msg;
  uint64_t *concat_msg;

  Serial.begin(115200);

  msg.data[0] = 0x01;
  msg.data[1] = 0x02;
  msg.data[2] = 0x03;
  msg.data[3] = 0x04;
  msg.data[4] = 0x05;
  msg.data[5] = 0x06;
  msg.data[6] = 0x07;
  msg.data[7] = 0x07;

  concat_msg = msg.data;

  union {
    uint64_t val;
    struct {
      uint32_t LSWord;
      uint32_t MSWord;
    };
  } out;

  out.val = *concat_msg;

  Serial.print(out.MSWord, HEX);
  Serial.println(out.LSWord, HEX);

}

void loop() {
  // put your main code here, to run repeatedly:

}

Have you thought of using a union?

Maybe you can use reinterpret_cast to create a pointer of uint64_T to the array. It seems to allow you to ride roughshod over the tiresome type restrictions.

...R

Robin2:
Maybe you can use reinterpret_cast to create a pointer of uint64_T to the array. It seems to allow you to ride roughshod over the tiresome type restrictions.

...R

yep, reinterpret_cast did the job! Thanks Robin2!

typedef struct
{
  uint16_t id;
  struct {
    int8_t rtr : 1;
    uint8_t length : 4;
  } header;
  uint8_t data[8];
} tCAN;

void setup() {
  tCAN msg;
  uint64_t *concat_msg = reinterpret_cast<uint64_t*>(msg.data);
  //OR in C style
  //uint64_t *concat_msg = (uint64_t*)msg.data;

  Serial.begin(115200);

  msg.data[0] = 0x11;
  msg.data[1] = 0x22;
  msg.data[2] = 0x33;
  msg.data[3] = 0x44;
  msg.data[4] = 0x55;
  msg.data[5] = 0x66;
  msg.data[6] = 0x77;
  msg.data[7] = 0x88;

  union {
    uint64_t val;
    struct {
      uint32_t LSDWord;
      uint32_t MSDWord;
    };
  } out;

  out.val = *concat_msg;

  Serial.print(out.MSDWord, HEX);
  Serial.println(out.LSDWord, HEX);

}

void loop() {
  // put your main code here, to run repeatedly:

}