I’m trying to write some code that uses boost::asio’s sockets to send a message from one end (the client) to another (the server).
My particular goal right now is to prepend every message being sent with a 1-byte unsigned integer (uint8_t) telling the receiver how many bytes long the rest of the message is.
Note that the reason I’m storing and transferring the size as a uint8_t instead of a size_t is because I want to ensure that it will be exactly 1 byte on both machines. A little googling has indicated that size_t can be of a different size on machine A versus machine B, which could mess things up.
So here I’m calculating the length of the message. The message consists of just two parts: a uint16_t, followed by a variable “data” which is a (void*)-cast chunk of memory that will serve varying purposes (the target machine has ways of interpreting that data, but I won’t get into that here).
uint8_t sizeOfMessage = sizeof(uint16_t) + sizeof(data);
In this example, sizeof(data) == 4, so sizeOfMessage should equal 6 (since uint16_t is a 2-byte integer). However, if I std::cout << sizeOfMessage, what’s displayed is not 6, but a special character: a spade (as in the suit of cards). Looking at the data in VS2010’s debugger, it shows up as 6 ‘-‘ . However, if I define sizeOfMessage as a size_t and print that out, everything is fine (but of course, I can’t send that over the network because the size in bytes of a size_t is not guaranteed from one machine to the next).
I take this to mean something is going wrong in how size_t is being cast into a uint8_t after the arithmetic. sizeof returns a size_t, so what my code is doing is adding two size_t’s and then casting that into a uint8_t.
Am I correct in my conclusion that the value is not being cast correctly? If so, how can I solve this?
Thanks in advance.
The value being assigned to your little (uint8_t) variable is not a printable ASCII character code that would display like ‘6’. Instead, it is a binary value, which is equivalent to coding ‘\006’ in your source code. If your data transfer protocol does work with binary code bytes, you’re probably good to go. What does the receiving program get in its instance of (uint8_t) which it reads one byte (char) into? And of course using (uint8_t) limits your total message length to 0 through 255 (but you knew that).