0

I am trying to serialize an object for sending in a socket, but for some reason, when i add to the string stream using <<, I'm also adding '0b' after it, i've tried looking for something that may cause this (such as a fault data type) but so far i came up with nothing.

this is my object before in memory before the serialization -

01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 03 0b 00 cc ff 00 00 00

this is the memory of the ostream that i use for the serialization -

01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 03 0b 03 0b 00 ff 00 00 00

this is the class itself and the overloading for serialization

`

    std::ostream& operator << (std::ostream& os, Header H)
    {
        os << H.CID;
        os << H.Version;
        os << H.FirstTwoCode;
        os << H.LastTwoCode;
        os.write(reinterpret_cast<const char*>(&H.Payload_size), sizeof(int));
        return os;
    }

class Header
{   
    UINT8 CID[CLIENTID_BYTE_SIZE];
    unsigned char Version;
    unsigned char FirstTwoCode;
    unsigned char LastTwoCode;
    int Payload_size ;
}
    Header::Header(UINT8 clientID[CLIENTID_BYTE_SIZE], int request_code, int PL_SIZE)
    {
        memcpy(CID, clientID, CLIENTID_BYTE_SIZE);
        Version = char(VERSION_NUMBER);
        FirstTwoCode = char(request_code / 100);
        LastTwoCode = char(request_code % 100);
        Payload_size = PL_SIZE;
    }

`

I've tried searching the web, and gone over my a lot of times, i think that it may have something to do with me saving integers inside chars, and the casting is doing something, but I'm not sure.

1
  • 1
    Questions seeking debugging help should generally provide a minimal reproducible example of the problem, which includes a function main and all #include directives. This allows other people to easily test your program, by simply using copy&paste. Commented Nov 7, 2022 at 0:36

1 Answer 1

1

Your bug is in this line:

os << H.CID;

It calls the unsigned char overload of (2) here: https://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt2, which means it just writes the memory of your Header object until the first null byte.

To achieve what you actually wanted, you can do something like

os.write(reinterpret_cast<char const*>(H.CID), CLIENTID_BYTE_SIZE);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.