Question

I'm using the following code to write number in hex to a MIDI file. It's to specify the track length - and the MIDI format requires a 32-bit hex value..

This is the code I'm using, where 'length' stores the number of bytes in the MIDI track -

int length;

char lenShort[3] = { 0x00, 0x00, 0x00 };
char lenLong[2] = { 0x00, 0x00 };

// create length 32-bit hex
if (length>255) {
    [contents appendBytes:&lenLong length:2];
    [contents appendBytes:&length length:2];
} else {
    [contents appendBytes:&lenShort length:3];
    [contents appendBytes:&length length:1];
}

It works fine with low numbers - for example, when length=57, it spits out 00000039 in hex, which is fine.

But for higher numbers, such as length=295, it gives me this - 00002701, which is wrong (it's 9985 in decimal)..

I discovered that I need to reverse the two last bytes - and I've been trying all sorts of 'unsigned longs' and 0xFFFFFFF things, but I don't really know what i'm doing, and nothing is working (I didn't pay attention in Hex classes at school!)

Can someone give me an easy way (in C or Obj-C) to switch the last two bytes around?

Was it helpful?

Solution

If I see it correctly, you want to write the length as an 32-bit integer in big-endian byte order. This can simply be done as:

int length = ...
uint32_t lengthBE = OSSwapHostToBigInt32(length);
[contents appendBytes:&lengthBE length:4];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top