3

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

  • 1
    possible duplicate .. http://stackoverflow.com/questions/1305225/best-way-to-serialize-a-nsdata-into-an-hexadeximal-string – Amar May 13 '13 at 11:46
  • Your code looks OK to me. What is the problem? – Martin R May 13 '13 at 12:03
  • @mango: What is not OK? What output do you get? What output do you expect? – Martin R May 13 '13 at 12:29
  • accdc6f2 1dd0e877 my nsdata when i printed . –  May 13 '13 at 12:30
  • iam expecting value like 826ad07e9a2a565e –  May 13 '13 at 12:32
  • @mango: What is the output of `NSLog(@"%@", string)` ? Is that not what you expect? – Martin R May 13 '13 at 12:34
  • its not the correct answer ..its some hex –  May 13 '13 at 12:42
  • 1
    @mango: Please show the **input**: `NSLog(@"%@", result)` and the **output**: `NSLog(@"%@", string)` and what you **expect**, otherwise it is very difficult to help!! – Martin R May 13 '13 at 12:46
  • 2
    Possible duplicate of [How to convert an NSData into an NSString Hex string?](https://stackoverflow.com/questions/7520615/how-to-convert-an-nsdata-into-an-nsstring-hex-string) – Cœur Sep 29 '17 at 02:19

5 Answers5

14

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];
}

@end
jjrscott
  • 1,386
  • 12
  • 16
John
  • 2,640
  • 1
  • 16
  • 16
3

The easiest solution is to loop thru the bytes of the NSData and construct the NSString from it. Use [yourData bytes] to access the bytes, and build the string into an NSMutableString.

Here is an example by implementing this using a category of NSData

interface NSData(Hex)
-(NSString*)hexRepresentationWithSpaces_AS:(BOOL)spaces;
@end

@implementation NSData(Hex)
-(NSString*)hexRepresentationWithSpaces_AS:(BOOL)spaces
{
    const unsigned char* bytes = (const unsigned char*)[self bytes];
    NSUInteger nbBytes = [self length];
    //If spaces is true, insert a space every this many input bytes (twice this many output characters).
    static const NSUInteger spaceEveryThisManyBytes = 4UL;
    //If spaces is true, insert a line-break instead of a space every this many spaces.
    static const NSUInteger lineBreakEveryThisManySpaces = 4UL;
    const NSUInteger lineBreakEveryThisManyBytes = spaceEveryThisManyBytes * lineBreakEveryThisManySpaces;
    NSUInteger strLen = 2*nbBytes + (spaces ? nbBytes/spaceEveryThisManyBytes : 0);

    NSMutableString* hex = [[NSMutableString alloc] initWithCapacity:strLen];
    for(NSUInteger i=0; i<nbBytes; ) {
        [hex appendFormat:@"%02X", bytes[i]];
        //We need to increment here so that the every-n-bytes computations are right.
        ++i;

        if (spaces) {
            if (i % lineBreakEveryThisManyBytes == 0) [hex appendString:@"\n"];
            else if (i % spaceEveryThisManyBytes == 0) [hex appendString:@" "];
        }
    }
    return [hex autorelease];
}
@end





  NSData* data = ...
NSString* hex = [data hexRepresentationWithSpaces_AS:YES];
Jitendra
  • 5,055
  • 2
  • 22
  • 42
2

This is conversion by integer operations:

-(NSString*)hex:(NSData*)data{
     NSMutableData *result = [NSMutableData dataWithLength:2*data.length];
     unsigned const char* src = data.bytes;
     unsigned char* dst = result.mutableBytes;
     unsigned char t0, t1;

     for (int i = 0; i < data.length; i ++ ) {
          t0 = src[i] >> 4;
          t1 = src[i] & 0x0F;

          dst[i*2] = 48 + t0 + (t0 / 10) * 39;
          dst[i*2+1] = 48 + t1 + (t1 / 10) * 39;
     }

     return [[NSString alloc] initWithData:result encoding:NSASCIIStringEncoding];
}
Denis Kreshikhin
  • 8,856
  • 9
  • 52
  • 84
0

Swift 2 version

private let kHexChars = Array("0123456789abcdef".utf8) as [UInt8];

extension NSData {

    public func hexString() -> String {
        guard length > 0 else {
            return ""
        }

        let buffer = UnsafeBufferPointer<UInt8>(start: UnsafePointer(bytes), count: length)
        var output = [UInt8](count: length*2 + 1, repeatedValue: 0)
        var i: Int = 0
        for b in buffer {
            let h = Int((b & 0xf0) >> 4)
            let l = Int(b & 0x0f)
            output[i++] = kHexChars[h]
            output[i++] = kHexChars[l]
        }

        return String.fromCString(UnsafePointer(output))!
    }
}
Quanlong
  • 24,028
  • 16
  • 69
  • 79
0

This answer is in Swift 4.2 running in an Xcode 10 Playground.

import Foundation

let d = Data(bytes: [0x3f, 0x09, 0x0a, 0xa3, 0x01])
let s:String = d.compactMap({ String(format: "%02x ", $0) }).joined()
print(s)

Here is the output:

3f 09 0a a3 01 
Jeff
  • 3,829
  • 1
  • 31
  • 49