I'm working on a project with flex, bison and c and I have to create a simple compiler for a simple language that generates Java bytecode directly in a Class file, then I would be able to execute it with java. The problem is about Java bytecode. I don't know how to write bytecode in Hexadecimal directly to a file from my C program.
I tried manually with Sublime Text to write "CAFE BABE" and save it with Hex encoding. It works. I tried different fwrite and fprintf but can't find the good way to do it.
FILE *dest = fopen("HelloWorld.class", "wb");
fwrite("CAFEBABE", sizeof(unsigned int), 4, dest);
I also saw some fprintf with 02x...
fprintf(dest, "%02x", "0xCA");
I really don't understand how to write directly with hex encoding...
Thanks you so much for any help.
Hex is a text representation of numbers. You don't want to write hex; you want to write the actual numbers.
To produce the four bytes CA FE BA BE, you can use any of the following:
const unsigned char* bytes = (const unsigned char*)"\xCA\xFE\xBA\xBE";
unsigned char bytes[] = "\xCA\xFE\xBA\xBE";
unsigned char bytes[] = { 0xCA, 0xFE, 0xBA, 0xBE };
As for outputting them, fprintf
is not ideal. While you could use the %s
format specifier if you made sure the data was NUL-terminated, you couldn't actually output a NUL using it. On the other hand, fwrite
is intended to write arbitrary bytes.