如何将128位UUID存储到16字节ASCII NSString中

时间:2012-07-06 05:39:18

标签: objective-c ios nsstring ascii uuid

我希望将128位UUID保存为16字节字符串,它将作为我的ManagedObject的索引属性存储在Core Data中,以确保插入和选择效率。

有没有办法将128位UUID存储到16字节的ASCII字符串中?如果有,如何在32字节UUID字符串和16字节ASCII字符串之间进行转换?

我尝试使用下面的代码将CFUUIDBytes存储到字符串中,但是在生成字符串后更改了值。 (如果任何字节值> 127;其值在生成的字符串中更改)

CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault);
CFUUIDBytes uuidBytes = CFUUIDGetUUIDBytes(uuidRef);
NSString *utf8String = [NSString stringWithFormat:@"%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c", 
                            uuidBytes.byte0, uuidBytes.byte1, uuidBytes.byte2,
                            uuidBytes.byte3, uuidBytes.byte4, uuidBytes.byte5,
                            uuidBytes.byte6, uuidBytes.byte7, uuidBytes.byte8,
                            uuidBytes.byte9, uuidBytes.byte10, uuidBytes.byte11,
                            uuidBytes.byte12, uuidBytes.byte13, uuidBytes.byte14,
                            uuidBytes.byte15];

1 个答案:

答案 0 :(得分:0)

在NSString courtesy上使用此类别:

   static unichar x (unsigned int); 

@implementation NSString (TWUUID) 

+ (NSString*) stringWithUniqueId 
{ 
    CFUUIDRef uuid = CFUUIDCreate(NULL); 
    CFUUIDBytes b = CFUUIDGetUUIDBytes(uuid); 
    unichar unichars[22]; 
    unichar* c = unichars; 
    *c++ = x(b.byte0 >> 2); 
    *c++ = x((b.byte0 & 3 << 4) + (b.byte1 >> 4)); 
    *c++ = x((b.byte1 & 15 << 2) + (b.byte2 >> 6)); 
    *c++ = x(b.byte2 & 63); 
    *c++ = x(b.byte3 >> 2); 
    *c++ = x((b.byte3 & 3 << 4) + (b.byte4 >> 4)); 
    *c++ = x((b.byte4 & 15 << 2) + (b.byte5 >> 6)); 
    *c++ = x(b.byte5 & 63); 
    *c++ = x(b.byte6 >> 2); 
    *c++ = x((b.byte6 & 3 << 4) + (b.byte7 >> 4)); 
    *c++ = x((b.byte7 & 15 << 2) + (b.byte8 >> 6)); 
    *c++ = x(b.byte8 & 63); 
    *c++ = x(b.byte9 >> 2); 
    *c++ = x((b.byte9 & 3 << 4) + (b.byte10 >> 4)); 
    *c++ = x((b.byte10 & 15 << 2) + (b.byte11 >> 6)); 
    *c++ = x(b.byte11 & 63); 
    *c++ = x(b.byte12 >> 2); 
    *c++ = x((b.byte12 & 3 << 4) + (b.byte13 >> 4)); 
    *c++ = x((b.byte13 & 15 << 2) + (b.byte14 >> 6)); 
    *c++ = x(b.byte14 & 63); 
    *c++ = x(b.byte15 >> 2); 
    *c = x(b.byte15 & 3); 
    CFRelease(uuid); 
    return [NSString stringWithCharacters: unichars length: 16];
} 
@end

unichar x (unsigned int c)
{
    if (c < 26) return 'a' + c;
    if (c < 52) return 'A' + c - 26;
    if (c < 62) return '0' + c - 52;
    if (c == 62) return '$';
    return '_';
}


...


    NSLog(@"%u", [[NSString stringWithCString:[[NSString stringWithUniqueId] UTF8String] encoding:NSASCIIStringEncoding] length]);