复制不同数据类型的缓冲区内容(Copying buffer contents of different data types)

编程入门 行业动态 更新时间:2024-10-11 19:21:39
复制不同数据类型的缓冲区内容(Copying buffer contents of different data types)

我正在为一个在MSP430控制器上运行的modbus协议编写代码。 响应缓冲区(全局)是一个8位数据的数组,通过它可以在串行UART上发送对已处理请求的响应。 现在,我的问题是生成的响应具有不同数据类型的组合。 即uint8,uint32,float。 如何使用全局响应缓冲区发送此数据?

对于浮动,我尝试使用memcpy,这似乎工作正常。 有没有更好更有效的方法? 因为帧大小很大(比如20-30字节)。 这是我试图做的一个演示

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; }

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

For float, i have tried using memcpy and this seems to be working fine. Is there any better and efficient way? Cuz the frame size is large (say 20-30 bytes). Here is a demo of what i've tried 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; }

最满意答案

随着铸造和分配。 例如

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

将myval复制到globalbuf的前4个字节中。

注意对齐问题:在您的平台上分配或读取不是该类型大小的整数倍的地址的值可能是非法的或昂贵的。 例如地址0,4,8等是放置uint32的好地方。

假设您的globalbuf从一个漂亮的圆形地址开始。

With casting and assignment. E.g.

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

copies myval into the first 4 bytes of globalbuf.

Beware of alignment issues: it may be illegal or expensive on your platform to assign or read values to/from addresses that aren't whole multiples of that type size. For example address 0,4,8 etc. are OK places to put a uint32.

This assumes your globalbuf starts on a nice round address..

更多推荐

本文发布于:2023-07-27 15:23:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1292372.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:缓冲区   数据类型   内容   Copying   types

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!