Convert NSString Hex to int Decimal Value ,iOS



-(void)FunTest{
    NSString*  mDataStaring = @"1234";
    NSString *subStr =@"";
    NSUInteger tlen=mDataStaring.length;
    for(int i=0;i<tlen;i=i+2){
      subStr = [mDataStaring substringWithRange:NSMakeRange(i, 2)];
      int value=[self Fun_ConvertStringToInt:subStr];
      NSLog(@"value=%d\n", value);
    }
}

-(int)Fun_ConvertStringToInt:(NSString*)iDataStaring{
    NSData* theData=[self bytesStringToData:iDataStaring];
    
    int *values = [theData bytes];
    NSUInteger cnt = [theData length];
    return values[0];
}
-(NSData*)bytesStringToData:(NSString*)bytesString
{
    if (!bytesString || !bytesString.length) return NULL;
    // Get the c string
    const char *scanner=[bytesString cStringUsingEncoding:NSUTF8StringEncoding];
    char twoChars[3]={0,0,0};
    long bytesBlockSize = bytesString.length/2;
    long counter = bytesBlockSize;
    Byte *bytesBlock = malloc(bytesBlockSize);
    if (!bytesBlock) return NULL;
    Byte *writer = bytesBlock;
    while (counter--) {
        twoChars[0]=*scanner++;
        twoChars[1]=*scanner++;
        *writer++ = strtol(twoChars, NULL, 16);
    }
    return[NSData dataWithBytesNoCopy:bytesBlock length:bytesBlockSize freeWhenDone:YES];
}

Screen Shot 2014-11-20 at 10.56.00 AM


Leave a Reply