I'm working on some code right now where the goal is to take in a byte stream and grab the data from the body of a message. The data is 10 bytes long and is meant to be translated into hex. Specifically, the 10 bytes coming in look like 01000200030004000500 or 01010201030104010501 (with implied 0x in front of each).
The code does this, but in my opinion it's not very pretty, so I was hoping to get help in improving both my own code and learning about a more effective way of grabbing an "uneven" amount of bytes (i.e. not the size of a data type for an easy memcpy
). I've seen suggestions for using an array, but I wasn't sure if memcopying or endianness changes would complicate its use.
case MyMessage:
{
std::string s;
unsigned int i,j;
// bytes are of type unsigned char*
// each hex value is 4 bits
memcpy(&i, bytes, sizeof(i)); // Bytes 0, 1, 2, 3
i = ntohl(i); // 01000200 or 01010201
memcpy(&j, bytes + 4, sizeof(j)); // Bytes 4, 5, 6, 7
j = ntohl(j); // 03000400 or 03010401
unsigned short k;
memcpy(&k, bytes + 8, sizeof(k)); // Bytes 8, 9
k = ntohs(k); // 0500 or 0501
std::ostringstream iS, jS, kS;
iS << std::hex << (i);
s += "0" + iS.str(); // Have to shove "0" at front when dropped
jS << std::hex << (j);
s += "0" + jS.str();
kS << std::hex << (k);
s += "0" + kS.str();
// In my actual code, these strings are constants
if (s == "01000200030004000500")
{
s = "Off";
}
else if (s == "01010201030104010501")
{
s = "On";
}
else
{
s = "ERROR";
}
return s;
}