2

I want to test serialized data conversion in my application, currently the object is stored in file and read the binary file and reloading the object.

In my unit test case I want to test this operation. As the file operations are costly I want to hard code the binary file content in the code itself.

How can I do this?

Currently I am trying like this,

std::string FileContent = "\00\00\00\00\00.........";

and it is not working.

13
  • use with x prefix. e.g. \x00\x00 etc Commented Jul 22, 2016 at 15:15
  • 1
    Using std::string for binary data, beuhh... It would be simpler and cleaner to use a plain char array or if you don't like plain arrays a std::array or std::vector of characters. You would avoid stupid errors of stopping on first null when initializing from a const char *. Commented Jul 22, 2016 at 15:20
  • 3
    Why not use a std::vector<uint8_t> rather than a string? Commented Jul 22, 2016 at 15:23
  • 2
    @GilsonPJ doesn't sound convincing Commented Jul 22, 2016 at 15:27
  • 1
    @GilsonPJ: try this: std::vector<uint8_t> FileContent = { 0x00, 0x00, 0x00, 0x00, 0x00, ... }; Commented Jul 22, 2016 at 15:42

2 Answers 2

2

You're right that a string can contain '\0', but here you're still initializing it from const char*, which, by definition, stops at the first '\0'. I'd recommend you to use uint8_t[] or even uint32_t[] (that is, without passing to std::string), even if the second might have up to 3 bytes of overhead (but it's more compact when in source). That's e.g. how X bitmaps are usually stored.

Another possibility is base64 encoding, which is printable but needs (a relatively quick) decoding.

If you really want to put the const char[] to a std::string, first convert the pointer to const char*, then use the two-iterator constructor of std::string. While it's true that std::string can hold '\0', it's somewhat an antipattern to store binary in a string, thus I'm not giving the exact code, just the hint.

Sign up to request clarification or add additional context in comments.

Comments

2

The following should do what you need, however probably not recommended as most people wouldn't expect an std::string to contain null bytes.

std::string FileContent { "\x00\x00\x00\x00\x00", 5 };

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.