C++: How to add raw binary data into source with Visual Studio?
The easiest and most portable way would be to write a small program which converts the data to a C++ source, then compile that and link it into your program. This generated file might look something like:
unsigned char rawData[] =
{
0x12, 0x34, // ...
};
There are tools for this, a typical name is "bin2c". The first search result is this page.
You need to make a char
array, and preferably also make it static const
.
In C:
Some care might be needed since you can't have a char
-typed literal, and also because generally the signedness of C's char
datatype is up to the implementation.
You might want to use a format such as
static const unsigned char my_data[] = { (unsigned char) 0xfeu, (unsigned char) 0xabu, /* ... */ };
Note that each unsigned int
literal is cast to unsigned char
, and also the 'u' suffix that makes them unsigned.
Since this question was for C++, where you can have a char
-typed literal, you might consider using a format such as this, instead:
static const char my_data[] = { '\xfe', '\xab', /* ... */ };
since this is just an array of char, you could just as well use ordinary string literal syntax. Embedding zero-bytes should be fine, as long as you don't try to treat it as a string:
static const char my_data[] = "\xfe\xdab ...";
This is the most compact solution. In fact, you could probably use that for C, too.