Reversing endianness with memcpy
I'm writing a method that creates an in-memory WAV file. The first 4 bytes of the file should contain the characters 'RIFF', so I'm writing the bytes like this:
Byte *bytes = (Byte *)malloc(len); // overall length of file
char *RIFF = (char *)'RIFF';
memcpy(&bytes[0], &RIFF, 4);
The problem is that this writes the first 4 bytes as 'FFIR', thanks to little-endianness. To correct this problem, I'm just doing this:
Byte *bytes = (Byte *)malloc(len);
char *RIFF = (char *)'FFIR';
memcpy(&bytes[0], &RIFF, 4);
This works, but is there a better-looking way of getti开发者_Python百科ng memcpy
to reverse the order of the bytes it's writing?
You're doing some bad things with pointers (and some weird but not wrong things). Try this:
Byte *bytes = malloc(len); // overall length of file
char *RIFF = "RIFF";
memcpy(bytes, RIFF, 4);
It'll work fine.
精彩评论