You should check what the other end is expecting (i.e. maybe the other end is expecting little-endian numbers, in which case everybody's happy, although that's not all that likely). If you need to convert to big-endian, then there is htons (since "network order" is another name for "big-endian").
This is undefined behavior (new and free).
Originally Posted by tabstop
But what I don't understand is that since you have the data in a string, why not simply do
Are you implying that your string consists of a number of shorts added together? That is, if we do
Then p will be the first block of data and p the next, etc?
const short* p = reinterpret_cast<const short*>(package.c_str());
That does sound reasonable. There are spaces between the hex values, but I can easily read them all into a string without spaces and send them without risk of flipping anything.
I just talked to the guy working the other end and he is just dealing with the 1's and 0's on his end, knowing this information, sending the data in a string would be easier. Earlier this week he gave me the impression that he was expecting an array he could read to fly out the other side.
Gotta love introverted programmers who don't communicate and waste your time :-(
Mmm. Does he want the values, or the textual representation? That is, if you have 0x1234, you can send two bytes 0x12 and 0x34 (in some order), or you can send the five bytes 0x31 (ASCII '1'), 0x32, 0x33, 0x34, 0x00 (for the end of the string).
He wants the actual values, padded with 0's. So if the number is 0x0F it needs to be sent as 000F. I think I have that already figured out though, but thank you for all the help! Even if I am not using the original scheme, I learned some new tricks and a bit about Endians so it was a worth-while detour.
Then you have to make sure you pad the values correctly when you add them to the string. I don't know how you are receiving these values, though.
But if you have an array of shorts, you might actually do this instead:
This will avoid endianess issues.
// Let input be an array of shorts whose length is input_length
for (int i = 0; i < input_length; i++)
data.push_back(input[i] & 0x00FF);
data.push_back((input[i] & 0xFF00) >> 8);