Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

To byte conversion in c++

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading