0

I have a C char array in iOS that looks like this:

static char aStr[MY_STRING_LENGTH] = {0xc0,0xa7,0x82};

When I inspect it on the console (p aStr), I get output that looks like:

(char [MY_STRING_LENGTH]) $1 = "\xc0\xa7\x82"

and that is all fine. However, I need to put that original string in a plist, and read it in as config data. If I type my entry in the plist as a NSString, how can I get the C char array out with the same values? So far, everything I have tried seems to translate the hex values into something else.

I have tried things like:

NSString *newStr = [stringFromPlist UTF8String];

Or breaking the NSString into an array with:

NSArray *arr = [stringFromPlist componentsSeparatedByString:@","];

and then iterating and converting with:

char newArr[MY_STRING_LENGTH];

for (int i = 0; i < MY_STRING_LENGTH; i++) {
    newArr[i] = [arr[i] UTF8String];
}

but so far nothing seems to do what I need. I keep ending up with values in the char array that contain the "0x" instead of the "\x".

My C chops are FAR too rusty for this, so I am hoping someone can point out my error.

Cheers!

4

1 回答 1

1

我不知道是否有更优雅的解决方案,但您可以尝试:

NSString *stringFromPlist = @"0xc0,0xa7,0x82";
NSArray *arr = [stringFromPlist componentsSeparatedByString:@","];
char newArr[MY_STRING_LENGTH];
for (int i = 0; i < MY_STRING_LENGTH; i++) {
    unsigned result = 0;
    NSScanner *scanner = [NSScanner scannerWithString:arr[i]];
    [scanner scanHexInt:&result];
    newArr[i] = result;
}
于 2013-12-09T06:44:11.633 回答