I am using this code:
int number; //=smth
unsigned char sendBuffer[255];
sendBuffer[0] = number & 0xFF;
sendBuffer[1] = (number >> 8) & 0xFF;
sendBuffer[2] = (number >> 16) & 0xFF;
sendBuffer[3] = (number >> 24) & 0xFF;
to put number in byte array sendBuffer.
My question is:
Say I want to embed now two numbers in the byte array, shall I proceed like this?
sendBuffer[0] = number & 0xFF; sendBuffer[1] = (number >> 8) & 0xFF; sendBuffer[2] = (number >> 16) & 0xFF; sendBuffer[3] = (number >> 24) & 0xFF; sendBuffer[4] = number2 & 0xFF; sendBuffer[5] = (number2 >> 8) & 0xFF; sendBuffer[6] = (number2 >> 16) & 0xFF; sendBuffer[7] = (number2 >> 24) & 0xFF;Will this work even if
numberis of size say 8 or 6 bytes? (I am saying this because on some platforms the int maybe 4 bytes or 6 right? So I was thinking if the above code also works when number is 6 bytes? Further thing to note is that even if it is 6 bytes, but I only store 4 byte integer inside it, will above code work?).This buffer I usually store on some memory of a card and I don't have problems reading it back (e.g., endiannes etc. issues, the byte array when reading seems to come in the order I saved).
Finally, how to reconstruct the integer from the byte array
sendBuffer?
memcpyon POD types or primitives is allowed. Look at protobuf, Boost Serialization or Boost Spirit, thoughstd::copy(which will internally almost always usememcpyormemmovefor POD types).