Convert NSString Hex to int Decimal Value ,iOS

November 20, 2014   ·   0 Comments

Screen Shot 2014-11-20 at 10.56.00 AM

-(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

shareShare on FacebookShare on Google+Share on LinkedInEmail this to someonePrint this pageBuffer this pageDigg thisFlattr the authorShare on RedditPin on PinterestShare on StumbleUponShare on TumblrTweet about this on Twitter

By


Readers Comments (0)


You must be logged in to post a comment.

PowenKo’s Online Store

powenko_arduinoBook
iOS Tutorial9

Amazon

adsbygoogle

Recent Posts

Categories

Amazon