简体   繁体   中英

How can i convert NSString to uint8_t array

I have an NSString like so: 850210

How can i convert it to uint8_t data[]={0x85,0x02,0x10};

Could someone please help me out with this??

BR, Suppi

#import <Foundation/Foundation.h>
static NSString * const hexString = @"850210";

int main (int argc, const char * argv[])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    uint8_t         data[3]={0};
    const char      * theUniChar = hexString.UTF8String;

    for( int i = 0, c = (int)strlen(theUniChar)/2; i < c && i < sizeof(data)/sizeof(*data); i++ )
    {
        int     theNum = 0;
        sscanf( theUniChar + 2*i, "%2x", &theNum );
        data[i] = theNum;
    }

    printf( "{%x,%x,%x}\n", data[0],data[1],data[2] );


    [pool drain];
    return 0;
}

Loop over the string and start by checking for strings of length < 3. If it is just simply call intValue on the NSString itself and you have your first and only byte.

If it's larger than or equal to three start by reading in three numbers and checking if that is larger than 255. If it is re-read in the two bytes and check what value they have and that's a byte. If it's not then take the three first numbers and that's a byte.

Repeat this process on the remaining string that you have (a string created by disregarding the numbers you have already read in).

Good luck :)


I was assuming that string was in decimal format. If that's hex then simply read in two numbers at a time. And use this question to help you: How can I convert hex number to integers and strings in Objective C?


Second edit:

I have not tested this but you if there are any errors they should be easy to fix:

NSString *hexString = @"8510A0";
uint8_t *result = (uint8_t *)malloc(sizeof(uint8_t) * ([hexString length] / 2));
for(int i = 0; i < [hexString length]; i += 2) {
    NSRange range = { i, 2 };
    NSString *subString = [hexString subStringWithRange:range];
    unsigned value;
    [[NSScanner scannerWithString:subString] scanHexInt:&value];
    result[i / 2] = (uint8_t)value;
}
// result now contains what you want
free(result)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM