Copying buffer contents of different data types

I am writing code for the Modbus protocol that runs on an MSP430 controller. The response buffer (global) is an array of 8-bit data through which the response to the processed request must be sent via the serial UART. Now my problem is that the generated response has a combination of different data types. ie uint8, uint32, float. How do I send this data using the global response buffer?

For floats, I've tried using memcpy and it seems to work fine. Is there a better and more efficient way? Because the frame size is large (say 20-30 bytes). Here is a demo of what I was trying to do

int main() 
{ unsigned char buff[8]; //Global buffer 

float temp[2]; //temp buffer to store response values 

temp[0] = 0x00ef2212; 

memcpy(buff, temp, 8); 

printf("buff[0]= %u \n buff[1]= %u\n buff[2] = %u\n buff[3]= %u\n", buff[0],buff[1],buff
[2],buff[3]); 

return 0; 
} 

      

+3


source to share


3 answers


With casting and assignment. For example.

uint8 *globalbuf;
uint32 myval;
*(uint32*)globalbuf = myval;

      

copies myval to the first 4 bytes of globalbuf.



Beware of alignment issues: it may be illegal or costly on your platform to assign or read values ​​to / from addresses that are not integer multiples of this type. For example, address is 0,4,8, etc. is OK to put uint32.

This assumes your globalbuf starts with a nice round address.

+1


source


a simple implementation would be to create a response structure and memcpy response structure into a buffer

struct response {
   uint8 bytedata;
   uint32 intdata;
   float  floatdata;
};
memcpy((void *)uartbuffer,(void *)&response,sizeof(response));

      



Note: since it looks like you are working on a protocol, the endianess may already be specified and you may need to package the items according to a specific endian type and simple memcpy will not work and you may need to package the data types.

+1


source


How to consider using union to represent the same memory range to different data types?

typedef union {
    unsigned char buff[8];
    float temp[2];
} un;

un global_buffer;
// give global_buffer.buff some data.
un local_buffer;

local_buffer = global_buffer; 
// handle local_buffer.temp

      

0


source







All Articles