i tried making a c++ function that takes in a pointer and then returns a pointer to a char array representing the bytes
char* toBytes(void* src, int byteSize) {
char convertedToBytes[byteSize];
memcpy(&convertedToBytes, src, byteSize);
return _strdup(convertedToBytes);
}
though when using it and checking each char i see the output is 3 0 ffffffffd ffffffffd instead of 3 0 0, here is the full code:
int32_t i_lengthOfCommand = 3;
char *s_lengthOfCommand = toBytes(&i_lengthOfCommand);
printf("%x %x %x %x", s_lengthOfCommand[0], s_lengthOfCommand[1], s_lengthOfCommand[2], s_lengthOfCommand[3]);
stdout: 3 0 ffffffffd ffffffffd
PS: i know there is no support for big/little endian
>Solution :
I suggest using a std::string:
template<class T>
std::string toBytes(const T& src) {
return {reinterpret_cast<const char*>(&src),
reinterpret_cast<const char*>(&src) + sizeof src};
}
You can then use it with send() etc:
auto res = toBytes(i_lengthOfCommand);
send(sockfd, res.data(), res.size(), flags);