gpt4 book ai didi

ios - 如何将 CBUUID 转换为字符串

转载 作者:技术小花猫 更新时间:2023-10-29 10:29:09 25 4
gpt4 key购买 nike

我找不到任何官方方法从 CBUUID 中取回 UUID 字符串。这些 UUID 的长度可以是 2 或 16 个字节。

目标是将 CBUUID 作为字符串存储在某个文件中,然后使用 [CBUUID UUIDWithString:] 等复活。这是我目前所拥有的。

// 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 执行此操作:

@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。

关于ios - 如何将 CBUUID 转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13275859/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com