views:

860

answers:

3

Hi all,

I am looking for a nice-cocoa way to serialize a NSData object into an hexadecimal string. The idea is to serialize the deviceToken used for notification before sending it to my server.

I have the following implementation, but I am thinking there must be some shorter and nicer way to do it.

+ (NSString*) serializeDeviceToken:(NSData*) deviceToken
{
    NSMutableString *str = [NSMutableString stringWithCapacity:64];
    int length = [deviceToken length];
    char *bytes = malloc(sizeof(char) * length);

    [deviceToken getBytes:bytes length:length];

    for (int i = 0; i < length; i++)
    {
     [str appendFormat:@"%02.2hhX", bytes[i]];
    }
    free(bytes);

    return str;
}

Thanks for your inputs.

thomas

A: 

[deviceToken description]

you'll need to remove the spaces.

Personally I base64 encode the deviceToken, but it's a matter of taste.

Eddie
This does not get the same result.description returns :<2cf56d5d 2fab0a47 ... 7738ce77 7e791759>While I am looking for:2CF56D5D2FAB0A47....7738CE777E791759
sarfata
+5  A: 

What about:

const unsigned *tokenBytes = [deviceToken bytes];
NSString *hexToken = [NSString stringWithFormat:@"%08x%08x%08x%08x%08x%08x%08x%08x",
      ntohl(tokenBytes[0]), ntohl(tokenBytes[1]), ntohl(tokenBytes[2]),
      ntohl(tokenBytes[3]), ntohl(tokenBytes[4]), ntohl(tokenBytes[5]),
      ntohl(tokenBytes[6]), ntohl(tokenBytes[7])];
ianolito
This is by far the best solution so far. Thanks a lot.
sarfata
+1  A: 

Change "%08x" to "%08X" to get capital characters.

Dan Reese