1

I have an array full of NSString's in hex and what to create a char array from them. I'm not sure how this can be done.

So I have an array

NSArray *myArray = [NSArray arrayWithObjects:@"0xAA", @"0xBB", @"0xCC", nil];

from this I want to create a c char array, something similar to this

const unsigned char testing[] = { 0xAA, 0xBB, 0xCC };

Any advice would be appreciated

Thanks

2 Answers 2

3

You can take the NSScaner approach:

NSArray *myArray =
    [NSArray arrayWithObjects:@"0xAA", @"0xBB", @"0xCC", nil];
int size = [myArray count];
unsigned char testing[size];

unsigned holder;

for (int i = 0; i < size; ++i) {
    [[NSScanner scannerWithString:[myArray objectAtIndex:i]]
                       scanHexInt:&holder];
    testing[i] = holder; /* or check for errors before assigning */
}

Or the C approach:

for (int i = 0; i < size; ++i) {
    sscanf([[myArray objectAtIndex:i] UTF8String], "%x", &holder);
    testing[i] = holder; /* same thing */
}
Sign up to request clarification or add additional context in comments.

2 Comments

for the Obj-C approach, Xcode states that you can't initialize a parameter of type unsigned int* with value unsigned char* on the scanHexInt:testing+i line .... sorry new to C programming
Oh, sure. Sorry, I just typed in the code without much thinking. I updated the answer with a safer way of doing it.
3

using char testing[] you are defined an array of char. So just a string can be parsed into that array. You have to define

const unsigned char testing[][];

and in a loop fill it with this:

NSString *s = @"Some string";
const char *c = [s UTF8String];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.