I have a large message which must be initialized to default values. The message is a structure with many sub-structures, enums, etc. I have an automatically generated description file of the message, which contains the field-by-field parse of the message: field start byte, start bit, length, type, default value. I've implemented a mechanism which treats the message as a bits buffer and initializes it according to the description file. But.... I have a problem with floating point defaults. How do I make the automation of setting floating point variable bitwise?
Thanks!
Well, I've managed to solve it by myself. Assume the following:
MSG_STRUCT_TYPE OutputMsg; // e.g.750 bytes
int startByte = 28; // the start byte of floating point field in the message
float defVal = -1.75f; // the default value for the field above
Now, using the reinterpret_cast we can do the following manipulation:
unsigned char* bytes_to_set = reinterpret_cast<unsigned char*>(&defVal);
unsigned char* msgBuff = reinterpret_cast<unsigned char*>(&OutputMsg);
*reinterpret_cast<float*>(&msgBuf[startByte]) = *reinterpret_cast<float*>(bytes_to_set);
That do the job.
After implementing and checking njuffa 's comment bellow, I'm adding it as another (simplier and cleaner) answer:
unsigned char* msgBuff = reinterpret_cast<unsigned char*>(&OutputMsg);
memcpy(&msgBuf[startByte], &defVal, sizeof(float);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.