本文介绍了如何将CBUUID转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我找不到任何正式方法从CBUUID中取回UUID字符串。这些UUID可以是2或16个字节长。
I can't find any official way to get a UUID string back out of a CBUUID. These UUIDs can be 2 or 16 bytes long.
目标是将CBUUID存储在文件中的某个文件中,然后用[CBUUID UUIDWithString:]等复活。这是我到目前为止所拥有的。
The goal is to store CBUUIDs in a file somewhere as a string, and then resurrect with [CBUUID UUIDWithString:] etc. Here is what I have so far.
// returns a simple 4 byte string for 16bit uuids, 128 bit uuids are in standard 8-4-4-4-12 format
// the resulting string can be passed into [CBUUID UUIDWithString:]
+(NSString*)CBUUIDToString:(CBUUID*)cbuuid;
{
NSData* data = cbuuid.data;
if ([data length] == 2)
{
const unsigned char *tokenBytes = [data bytes];
return [NSString stringWithFormat:@"%02x%02x", tokenBytes[0], tokenBytes[1]];
}
else if ([data length] == 16)
{
NSUUID* nsuuid = [[NSUUID alloc] initWithUUIDBytes:[data bytes]];
return [nsuuid UUIDString];
}
return [cbuuid description]; // an error?
}
推荐答案
我操纵了以下类别为CBUUID执行此操作:
I rigged up the following category to do this for CBUUID:
@interface CBUUID (StringExtraction)
- (NSString *)representativeString;
@end
@implementation CBUUID (StringExtraction)
- (NSString *)representativeString;
{
NSData *data = [self data];
NSUInteger bytesToConvert = [data length];
const unsigned char *uuidBytes = [data bytes];
NSMutableString *outputString = [NSMutableString stringWithCapacity:16];
for (NSUInteger currentByteIndex = 0; currentByteIndex < bytesToConvert; currentByteIndex++)
{
switch (currentByteIndex)
{
case 3:
case 5:
case 7:
case 9:[outputString appendFormat:@"%02x-", uuidBytes[currentByteIndex]]; break;
default:[outputString appendFormat:@"%02x", uuidBytes[currentByteIndex]];
}
}
return outputString;
}
@end
对于此输入:
NSLog(@"UUID string: %@", [[CBUUID UUIDWithString:@"0bd51666-e7cb-469b-8e4d-2742f1ba77cc"] representativeString]);
NSLog(@"UUID string2: %@", [[CBUUID UUIDWithString:@"1800"] representativeString]);
它产生以下输出:
UUID string: 0bd51666-e7cb-469b-8e4d-2742f1ba77cc
UUID string2: 1800
并为16字节UUID保留适当的连字符,同时支持简单的2字节UUID。
and preserves the appropriate hyphenation for the 16 byte UUIDs, while supporting the simple 2-byte UUIDs.
这篇关于如何将CBUUID转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!