How to convert NSString to char

I am trying to convert NSStringto ResTypeas defined below in MacTypes.h.

FourCharCode // A 32-bit value made by packing four 1 byte characters together
typedef FourCharCode ResType;

I think I could use [aString getCharacters:range:], but is there a more direct way to do this conversion?

After you tried the suggestions from David, here is another piece of information.

I use GTResourceFork, a Cocoa shell to access resource loops. The method I'm calling is: - (NSArray *) usedResourcesOfType: (ResType) type;

If I hardcode the "RTF" value, I get the expected results. I cannot figure out how to convert an NSString containing "RTF" to a hard coded value. I created a test case using NSString getCharacters and getBytes, and they all give different integer values. How to convert NSString to give me the same integer value as hardcoded?

 Method used:       Value:  Casted int value:
 Hard Coded(Works): 'RTF ' '1381254688'
 getCharacters:     'RTF ' '5505106'
 getBytes(ASCII):   'RTF ' '541480018'
 getBytes(UTF8):    'RTF ' '541480018'

Thanks in advance, Spear

0
source share
1 answer

The problem with getCharacters:range:is that it gives you UTF-16 ( unichars) characters , while you want ASCII.

*(ResType*)[aString UTF8String] UTF-8 ( ASCII, ASCII), ResType. , , .

- getBytes:maxLength:usedLength:encoding:options:range:remainingRange: , NSASCIIStringEncoding NSUTF8StringEncoding, ResType, - 4 ( sizeof (ResType)).


:

, . , , . :

#include <Foundation/Foundation.h>

int main() {
    int code = 'RTF ';
    printf("'%c%c%c%c' = %d\n", ((char*)&code)[0], ((char*)&code)[1],
                                ((char*)&code)[2], ((char*)&code)[3],
                                code);
}

' FTR' = 1381254688. , NSString , :

  • ( ), 0 3 1 2.
  • , " ", .
  • ( ) characterAtIndex: . , characterAtIndex: UTF-16, ASCII, ASCII.
+1

Source: https://habr.com/ru/post/1772035/


All Articles