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.
char str[5];
str[4] = '\0';
long *code = (long *)str;
*code = 1919902568;
printf("%s\n", str);
In Swift you would use this function:
func str4 (n: Int) -> String
{
var s: String = ""
var i: Int = n
for var j: Int = 0; j < 4; ++j
{
s = String(UnicodeScalar(i & 255)) + s
i = i / 256
}
return (s)
}
This func will do the same like above in a third of the time:
func str4 (n: Int) -> String
{
var s: String = String (UnicodeScalar((n >> 24) & 255))
s.append(UnicodeScalar((n >> 16) & 255))
s.append(UnicodeScalar((n >> 8) & 255))
s.append(UnicodeScalar(n & 255))
return (s)
}
The reverse way will be:
func val4 (s: String) -> Int
{
var n: Int = 0
var r: String = ""
if (countElements(s) > 4)
{
r = s.substringToIndex(advance(s.startIndex, 4))
}
else
{
r = s + " "
r = r.substringToIndex(advance(r.startIndex, 4))
}
for UniCodeChar in r.unicodeScalars
{
n = (n << 8) + (Int(UniCodeChar.value) & 255)
}
return (n)
}