Use std::memcpy
, as in std::memcpy(data + 5, &someFloat, sizeof someFloat);
. It is defined by the rules of the C++ standard, unlike using reinterpret_cast
in the way shown in the question, and a good compiler will optimize it to simple load and store instructions if appropriate.
Note that the sizes of the objects being copied are dependent on the C++ implementation; it will be your responsibility to ensure they match the sizes as laid out in the buffer being sent. Also, the representations of objects are largely implementation-dependent, particularly the order in which their bytes are stored in memory, and so it is also your responsibility to make sure the representation matches what is expected in the message sent over the network. In some C++ implementations, you may need to reverse the bytes within objects. And you must ensure that the sending and receiving systems use the same format for float
, and so on.
CLICK HERE to find out more related problems solutions.