|
-
July 14th, 2011, 01:57 PM
#1
parse a string to bytearray to struct
I'm trying to parse a string into individual variables defined by a struct into a byte array. I want to pass the byte array to a com server object and not the string because it's smaller size, correct?
I wrote a function "GetByteArray" to parse the string into the byte array. The problem I have is the byte array does not cast back the floats into my TD struct. I also noticed the size of the byte array written is different than the structure. Why is that?
If there is better approach, please suggest one.
Code:
#include "stdafx.h"
#include <stdio.h>
#include <string>
struct TD
{
short sYear;
short sMonth;
short sDay;
float fVal1;
float fVal2;
};
void GetByteArray(const std::string& str, unsigned char* bytes)
{
// get chars 0-3 from str to get string for year
std::string strYear = str.substr(0,4);
short sYear = (short)atoi(strYear.c_str());
// get chars 5-6 from str to get string for month
std::string strMonth = str.substr(5,2);
short sMonth = (short)atoi(strMonth.c_str());
// get chars 8-9 from str to get string for day
std::string strDay = str.substr(8,2);
short sDay = (short)atoi(strDay.c_str());
// get chars 11-17 from str to get string for Val1
std::string strVal1 = str.substr(11,7);
float fVal1 = (float)atof(strVal1.c_str());
// get chars 19-25 from str to get string for Val2
std::string strVal2 = str.substr(19,7);
float fVal2 = (float)atof(strVal2.c_str());
size_t i = 0;
// cast strYear to short and append to byte array
memcpy(&bytes[i], &sYear, sizeof(short));
i += sizeof(short);
// cast strMonth to short and append to byte array
memcpy(&bytes[i], &sMonth, sizeof(short));
i += sizeof(short);
// cast strDay to short and append to byte array
memcpy(&bytes[i], &sDay, sizeof(short));
i += sizeof(short);
// cast strAsk to float and append to byte array
memcpy(&bytes[i], &fVal1, sizeof(float));
i += sizeof(float);
// cast strBid to float and append to byte array
memcpy(&bytes[i], &fVal2, sizeof(float));
i += sizeof(float);
}
int main(int argc, char* argv[])
{
// string to parse
std::string strData = "2011.06.30,1.40562,1.40559";
unsigned char MyBytes[sizeof(TD)];
GetByteArray(strData, MyBytes);
// i = 14 from GetByteArray
int i = sizeof(TD); // i = 16 from structure size
// error here! my floats in td are undefined
TD* td = (TD*)MyBytes;
return 0;
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|