Assign an array to an ESB Payload ?

Hi,

Currently tinkering with ESB comms, everything is fine but I was wondering whether there is a simple way to assign an array to a payload.
For now, I have 2 int variables, say 301 and 257 and I assign each digits to the payload:
tx_payload.data[0] = 3;
tx_payload.data[1] = 0;
tx_payload.data[2] = 1;
tx_payload.data[3] = 2;
tx_payload.data[4] = 5;
tx_payload.data[5] = 7;

and do the same on the RX side, decomposing them into numbers.

In order to assign those two int variables into the payload, I tried to achieve this into a char string (of 6) like "301257" and then assign this to tx_payload.data without success.

Is there any way to assign 2 int variables directly into the payload and the other way around, something like value1 = rx_payload.data[0..2] and value2 = rx_payload.data[3..5] ?

Any help or hint GREATLY appreciated

Steve

Parents
  • Hi Steve, the payload data is itself an array of unsigned 8-bit values (uint8_t).  There are many ways to do what you describe, but one way would be to dereference the array elements as pointers to 32-bit values and assign them directly.

    It might look something as follows (putty the values into variables is optional).

    uint32_t num1 = 301;
    uint32_t num2 = 257;
    *((uint32_t *) &tx_payload.data[0]) = num1;
    *((uint32_t *) &tx_payload.data[4]) = num2;
    tx_payload.length = sizeof(uint32_t) * 2;

    Then on the receiving side, do the opposite dereference the values from the received payload data.

    uint32_t num1, num2;
    num1 = *((uint32_t *) &rx_payload.data[0]);
    num2 = *((uint32_t *) &rx_payload.data[4]);

    You will probably want to familiarize yourself with how C handles pointers into arrays and type conversion.  It's quite a bit different than other languages that you may be more familiar with.

    Mike

  • Hi Mike

    Thanks for this reminder and solution. It's exactly what I need. 
    And guess what, I already used that in a C++ app back in... 1999. I was a bit rusted (no pun intended with Rust).

    I knew it was something like that but was struggling with the data[4] offset for the 2nd value. I worked around using a string but avoid unless conversions back and forth is always slimmer, faster and nicer.

    Perfect, you made my day.

    Steve

Reply
  • Hi Mike

    Thanks for this reminder and solution. It's exactly what I need. 
    And guess what, I already used that in a C++ app back in... 1999. I was a bit rusted (no pun intended with Rust).

    I knew it was something like that but was struggling with the data[4] offset for the 2nd value. I worked around using a string but avoid unless conversions back and forth is always slimmer, faster and nicer.

    Perfect, you made my day.

    Steve

Children
No Data
Related