Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
739 views
in Technique[技术] by (71.8m points)

ios - How can i convert NSdata to hex string?

i tried following codes for converting a NSData to hex string values but all are wrong?

here "result" is my NSdata

i need a hex string as output but iam not getting that

NSUInteger dataLength = [result length];
  NSLog(@"%d",dataLength);
    NSMutableString *string = [NSMutableString stringWithCapacity:dataLength*2];
   const unsigned char *dataBytes = [result bytes];
    for (NSInteger idx = 0; idx < dataLength; ++idx) {        [string appendFormat:@"%02x", dataBytes[idx]];
 }    
    NSLog(@"%@",string);

how can i convert this please

UPDATES: the result data contains encrypted string .i want to convert this to hex values

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is a category that I have for doing this. This just gives you all the characters of the data in hex. No line break or anything.

@implementation NSData (NSData_Conversion)

#pragma mark - String Conversion
- (NSString *)hexadecimalString
{
    /* Returns hexadecimal string of NSData. Empty string if data is empty.   */

    const unsigned char *dataBuffer = (const unsigned char *)[self bytes];

    if (!dataBuffer)
    {
        return [NSString string];
    }

    NSUInteger          dataLength  = [self length];
    NSMutableString     *hexString  = [NSMutableString stringWithCapacity:(dataLength * 2)];

    for (int i = 0; i < dataLength; ++i)
    {
        [hexString appendFormat:@"%02x", (unsigned int)dataBuffer[i]];
    }

    return [NSString stringWithString:hexString];
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...