Hacker News new | ask | show | jobs
by sillysaurus3 3329 days ago
To embed binary assets into any language, write a program that emits the binary as a string containing hex codes.

E.g. bytes [0, 12, 99] would become "\x00\x0C\x63".

Almost every language has facilities to treat a string as a set of bytes, so this works basically everywhere. It's nice because you don't need any special language-level support for it.

2 comments

While I do agree that it is possible to do something like that, I think we can all agree that the following (available in Rust) is soooooo much nicer:

    let stuff = include_bytes!("my.file");
While include_bytes is nice, xxd -i in a makefile is pretty workable solution in the scale of things.
Fair point, however I believe the OP made the game work for many different OSes, and I don't think xxd or Makefiles are the best when you have to deal with Windows (whereas Rust's include_bytes! provides a platform-independent solution).

I had never heard of xxd until your comment though, so thank you very much!

Somehow I'm reminded of the old adage "UNIX is IDE for C"
Now I have to rewrite my arcade game emulator in rust just so I can use that to load rom images...
include_bytes! is for compile-time inclusion of files though, not for runtime.
Yeah but when it only runs 15 games with a max size of 32K... But yeah it makes it non-distributable because it would then include the images.
C++ string literals usually have fairly low maximum length (C++ standard suggests 64K in [implimits/2.16]). Initialized arrays can be longer in practice but they also have a limit (the same standard suggests 16K but even that will give you 128Kb if you initialize uint64). Objcopy, as suggested elsewhere in the comments has more comfortable limits.