Wednesday, November 01, 2006

Converting NSString to OSType

OSTypes, formerly known as ResTypes, are four byte sequences to identify data formats and creator applications under MacOS X. To convert from NSString to OSType the straight forward solution might be:

OSType convertNSStringToOSType(NSString* str) {
OSType app = 0;
memcpy(&app, [str cstring],sizeof(app));
return app;
}

which works but of course ignores the encoding completely. So:

OSType convertNSStringToOSType(NSString* str) {
OSType app = 0;
NSData* data = [str dataUsingEncoding: NSUTF8StringEncoding];
[data getBytes:&app length:sizeof(app)];
return app;
}

This works great until moving the whole thing to Intel! For a java hacker puzzling at first but then, recalling computer architecture class, the endians! So a look in the Universal Binary Programming Guide yields

OSType convertNSStringToOSType(NSString* str) {
OSType app = UTGetOSTypeFromString((CFStringRef)str);
return app;
}

The CFString cast is okay http://www.cocoadev.com/index.pl?CFStringRef

0 Comments:

Post a Comment

<< Home