将NSData序列化为十六进制字符串的最佳方法我正在寻找一种很好的可可方式将NSData对象序列化为十六进制字符串。我们的想法是将用于通知的deviceToken序列化,然后再将其发送到我的服务器。我有以下实现,但我认为必须有一些更短更好的方法来实现它。+ (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;}
                    
                    
                3 回答
                            小怪兽爱吃肉
                            
                                
                            
                        
                        
                                                
                    TA贡献1852条经验 获得超1个赞
使用NSData的description属性不应被视为HEX编码字符串的可接受机制。该属性仅供说明,可随时更改。作为一个注释,在iOS之前,NSData描述属性甚至没有以十六进制形式返回它的数据。
很抱歉在解决方案上喋喋不休,但重要的是要花费精力对其进行序列化,而不需要支持除了数据序列化之外的其他方面的API。
@implementation NSData (Hex)- (NSString*)hexString{
    NSUInteger length = self.length;
    unichar* hexChars = (unichar*)malloc(sizeof(unichar) * (length*2));
    unsigned char* bytes = (unsigned char*)self.bytes;
    for (NSUInteger i = 0; i < length; i++) {
        unichar c = bytes[i] / 16;
        if (c < 10) {
            c += '0';
        } else {
            c += 'A' - 10;
        }
        hexChars[i*2] = c;
        c = bytes[i] % 16;
        if (c < 10) {
            c += '0';
        } else {
            c += 'A' - 10;
        }
        hexChars[i*2+1] = c;
    }
    NSString* retVal = [[NSString alloc] initWithCharactersNoCopy:hexChars length:length*2 freeWhenDone:YES];
    return [retVal autorelease];}@end- 3 回答
 - 0 关注
 - 738 浏览
 
添加回答
举报
0/150
	提交
		取消
	