iOS/C: Convert “integer” into four character string

The type you’re talking about is a FourCharCode, defined in CFBase.h. It’s equivalent to an OSType. The easiest way to convert between OSType and NSString is using NSFileTypeForHFSTypeCode() and NSHFSTypeCodeFromFileType(). These functions, unfortunately, aren’t available on iOS.

For iOS and Cocoa-portable code, I like Joachim Bengtsson’s FourCC2Str() from his NCCommon.h (plus a little casting cleanup for easier use):

#include <TargetConditionals.h>
#if TARGET_RT_BIG_ENDIAN
#   define FourCC2Str(fourcc) (const char[]){*((char*)&fourcc), *(((char*)&fourcc)+1), *(((char*)&fourcc)+2), *(((char*)&fourcc)+3),0}
#else
#   define FourCC2Str(fourcc) (const char[]){*(((char*)&fourcc)+3), *(((char*)&fourcc)+2), *(((char*)&fourcc)+1), *(((char*)&fourcc)+0),0}
#endif

FourCharCode code="APPL";
NSLog(@"%s", FourCC2Str(code));
NSLog(@"%@", @(FourCC2Str(code));

You could of course throw the @() into the macro for even easier use.

Leave a Comment