How-to emit and parse raw binary data using yaml-cpp
-
27-09-2019 - |
Question
Is it possible to emit and read(parse) binary data(image, file etc)? Like this is shown here: http://yaml.org/type/binary.html How can I do this in yaml-cpp?
Solution
As of revision 425, yes! (for emitting)
YAML::Emitter emitter;
emitter << YAML::Binary("Hello, World!", 13);
std::cout << emitter.c_str();
outputs
--- !!binary "SGVsbG8sIFdvcmxkIQ=="
The syntax is
YAML::Binary(const char *bytes, std::size_t size);
I wasn't sure how to pass the byte array: char
isn't necessarily one byte, so I'm not sure how portable the algorithm is. What format is your byte array typically in?
(The problem is that uint8_t
isn't standard C++ yet, so I'm a little worried about using it.)
As for parsing, yaml-cpp
will certainly parse the data as a string, but there's no decoding algorithm yet.
OTHER TIPS
Here it is answered how to read/parse binary data from a yaml file with the yaml-cpp library.
This answer assumes that you are able to load a YAML::Node node object from a yaml file - explained in the yaml-cpp tutorials: https://github.com/jbeder/yaml-cpp/wiki/Tutorial).
The code to parse binary data from a yaml node is:
YAML::Binary binary = node.as<YAML::Binary>();
const unsigned char * data = binary.data();
std::size_t size = binary.size();
Then you have an array of bytes "data" with a known size "size".