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?
2 Answers
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.

- 33,081
- 21
- 109
- 146
-
Is there a way to do it *without* base64 encoding first? I'd like users to be able to specify short binary strings without going through those extra steps – endolith Mar 13 '12 at 15:03
-
@endolith, what do you mean "without base64 encoding"? Can you give an example? (Maybe open a new question to ask?) – Jesse Beder Mar 13 '12 at 21:33
-
`SGVsbG8sIFdvcmxkIQ==` is base64 encoded. I'd like it to be encoded more like `48 65 6c 6c 6f 2c 20 57 6f 72 6c 64 21` – endolith Mar 13 '12 at 21:36
-
@endolith: Nevermind. The `!!binary` tag requires base64, but you can define your own tags and interpret them however you want. I used `add_implicit_resolver` to handle the hex strings without any tag at all. – endolith Mar 13 '12 at 23:45
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".

- 842
- 7
- 10

- 544
- 5
- 8