2014年6月20日 星期五

[iOS] Objective-c NSString to Hex string

Objective-c NSString to Hex string


NSData *data = [self parseMacAddress:@"AABBCCDDEEFF "];

NSLog(@"After transfer: %@", data); 
= > AABBCCDDEEFF (Hex)


- (NSData *)parseMacAddress:(NSString *)address {
    
    NSArray *components = [address componentsSeparatedByString: @"-"];
    NSString *mac = (NSString *)[components objectAtIndex:4];
    
    const char *buf = [mac UTF8String];
    NSMutableData *temp = [[NSMutableDataalloc] init];
    
    if (buf) {
        uint32_t len = strlen(buf);
        char singleNumberString[3] = {'\0', '\0', '\0'};
        uint32_t singleNumber = 0;
        for(uint32_t i = 0 ; i < len; i+=2)
        {
            if ( ((i+1) < len) && isxdigit(buf[i]) && (isxdigit(buf[i+1])) )
            {
                singleNumberString[0] = buf[i];
                singleNumberString[1] = buf[i + 1];
                sscanf(singleNumberString, "%x", &singleNumber);
                uint8_t tmp = (uint8_t)(singleNumber & 0x000000FF);
                [temp appendBytes:(void *)(&tmp)length:1];
            }
            else
            {
                break;
            }
        }
    }
    
    NSData *macData = temp;
    NSLog(@"%@", macData);
    return macData;

}

沒有留言:

張貼留言