Question

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!

Was it helpful?

Solution

I don't know if there is a more elegant solution, but you could try:

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top