MusiGenesis
MusiGenesis

Reputation: 75296

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

Upvotes: 1

Views: 1432

Answers (1)

Carl Norum
Carl Norum

Reputation: 224972

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.

Upvotes: 4

Related Questions