title: Casting/converting from size_t to uint8_t in C++?
body: <p>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).</p>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <p>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).</p>
  
  <pre><code>uint8_t sizeOfMessage = sizeof(uint16_t) + sizeof(data);
  </code></pre>
  
  <p>In this example, sizeof(data) == 4, so sizeOfMessage should equal 6 (since uint16_t is a 2-byte integer).  However, if I std::cout &lt;&lt; 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 <strong>6 '-'</strong> .  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).</p>
  
  <p>I take this to mean something is going wrong in how size_t is being cast into a uint8_t after the arithmetic.  <strong>sizeof</strong> returns a size_t, so what my code is doing is adding two size_t's and then casting that into a uint8_t.</p>
  
  <p>Am I correct in my conclusion that the value is not being cast correctly?  If so, how can I solve this?</p>
  
  <p>Thanks in advance.</p>