1

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 getting memcpy to reverse the order of the bytes it's writing?

MusiGenesis
  • 74,184
  • 40
  • 190
  • 334

1 Answers1

4

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.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469
  • +1, there are 2 problems, one is the line `char *RIFF = (char *)'RIFF';` which instead of assigning the address of 'RIFF' to the pointer, is directly assigning 'RIFF' as the **value** of the pointer. The second (which is why you are getting 'FFIR' and not gibberish or a crash) is the line `memcpy(&bytes[0], &RIFF, 4);` where you are passing the address of the pointer instead of the pointer itself. – tscho May 03 '11 at 19:11
  • I'm using `&bytes[0]` instead of `bytes` here because I have to do similar writes at other positions in the byte array besides the beginning. I assume this is what you meant by "weird but not wrong". – MusiGenesis May 03 '11 at 19:24
  • @MusiGenesis - that and casting the result of the `malloc()` call. Argubly casting that result *is* wrong, though. It's certainly unnecessary. – Carl Norum May 03 '11 at 19:25
  • it works with or without the cast. I assume malloc returns a byte pointer anyway, so the cast is certainly unnecessary, but why would it be *wrong*? – MusiGenesis May 03 '11 at 19:29
  • @MusiGenesis - it can hide `#include` errors. http://stackoverflow.com/questions/1565496/specifically-whats-dangerous-about-casting-the-result-of-malloc – Carl Norum May 03 '11 at 19:31