将 NSData 序列化为十六进制字符串的最佳方法 [英] Best way to serialize an NSData into a hexadeximal string

查看:34
本文介绍了将 NSData 序列化为十六进制字符串的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种不错的可可方式将 NSData 对象序列化为十六进制字符串.这个想法是在将用于通知的 deviceToken 发送到我的服务器之前对其进行序列化.

I am looking for a nice-cocoa way to serialize an NSData object into a 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;
}

推荐答案

这是我写的应用于 NSData 的类.它返回一个表示 NSData 的十六进制 NSString,其中数据可以是任意长度.如果 NSData 为空,则返回一个空字符串.

This is a category applied to NSData that I wrote. It returns a hexadecimal NSString representing the NSData, where the data can be any length. Returns an empty string if NSData is empty.

NSData+Conversion.h

#import <Foundation/Foundation.h>

@interface NSData (NSData_Conversion)

#pragma mark - String Conversion
- (NSString *)hexadecimalString;

@end

NSData+Conversion.m

#import "NSData+Conversion.h"

@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 appendString:[NSString stringWithFormat:@"%02lx", (unsigned long)dataBuffer[i]]];

    return [NSString stringWithString:hexString];
}

@end

用法:

NSData *someData = ...;
NSString *someDataHexadecimalString = [someData hexadecimalString];

这可能"比调用 [someData description] 然后去除空格、< 和 > 更好.剥离字符感觉太hacky"了.另外,您永远不知道 Apple 将来是否会更改 NSData 的 -description 格式.

This is "probably" better than calling [someData description] and then stripping the spaces, <'s, and >'s. Stripping characters just feels too "hacky". Plus you never know if Apple will change the formatting of NSData's -description in the future.

注意:有人联系我询问此答案中代码的许可.我在此将我在此回答中发布的代码的版权献给公共领域.

NOTE: I have had people reach out to me about licensing for the code in this answer. I hereby dedicate my copyright in the code I posted in this answer to the public domain.

这篇关于将 NSData 序列化为十六进制字符串的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆