Mike97
Mike97

Reputation: 605

nsstring to unsigned char []

I would convert

NSString *myString = @"0x10 0x1c 0x37 0x00"; //Aquired reading text file using NSString methods..

to

unsigned char convertedfrommyString[] = { 0x10, 0x1c, 0x37, 0x00 };

My goal is to aquiring them and then swap it using this code:

unsigned char convertedfrommyString[] = { 0x10, 0x1c, 0x37, 0x00 };
    int data = *((int *) convertedfromString);
    NSLog(@"log = %08x", data);

the output should be:

log = 00371c10

Any help?

EDIT

From both Jan Baptiste Younès and Sven I found the way to understand my problem and solve with this code:

NSString *myString = [[@"0x10 0x1c 0x37 0x00" stringByReplacingOccurrencesOfString:@"0x" withString:@""] stringByReplacingOccurrencesOfString:@" " withString:@""];
    unsigned result = 0;
    NSScanner *scanner = [NSScanner scannerWithString:myString];
    [scanner scanHexInt:&result];
    int reverse = NSSwapInt(result);
    NSLog(@"scanner: %8u", result);
    NSLog(@"bytes:%08x", result);
    NSLog(@"reverse:%08x (that is what i need!)", reverse);

Really OK! But can I accept two answer?

Upvotes: 0

Views: 776

Answers (2)

anon
anon

Reputation:

That's more than a simple conversion, you need to actually parse the values from your string. You can use NSScanner to do this.

NSScanner *scanner = [NSScanner scannerWithString: @"0x10 0x1c 0x37 0x00"];
unsigned char convertedfrommyString[4];
unsigned index = 0;
while (![scanner isAtEnd]) {
    unsigned value = 0;
    if (![scanner scanHexInt: &value]) {
        // invalid value
        break;
    }

    convertedfrommyString[index++] = value;
}

Of course this sample is missing error handling (the single values could not fit into an unsigned char or there could be more than four).

But this solved only half your problem. The other issue is converting this to an int. You did this by casting the unsigned char pointer to an int pointer. This is not portable and also not legal in C. To always get the result you want you should instead use bit shifts to assemble your int. So inside your loop you could do

result = result | (value << i);
i += 8;

instead of putting the values inside an unsigned char array. For this result and i should both be initialized to zero.

Upvotes: 2

Jean-Baptiste Yun&#232;s
Jean-Baptiste Yun&#232;s

Reputation: 36401

You may cut your original string at spaces and use the solution given here Objective-C parse hex string to integer. You can also use scanUpToString:intoString to parse upto space chars.

Upvotes: 1

Related Questions