我有一个NSString @“ 460046003600430035003900”,它代表十六进制颜色FF6C59。
如何从上述格式的字符串中获取十六进制颜色:
例如:
460046003500430032003000 = FF5C20
300030004200350033004500 = 00B53E
最佳答案
#import <Foundation/Foundation.h>
@interface WeirdFormatDecoder : NSObject
@end
@implementation WeirdFormatDecoder
+(NSString*) decode:(NSString*)string
{
if (!string) return @"";
NSAssert([string length]%2==0, @"bad format");
NSMutableString *s = [NSMutableString new];
for (NSUInteger i=0; i<[string length]-2; i=i+2) {
char c = [[string substringWithRange:NSMakeRange(i, 2)] integerValue];
if (c==0) continue;
else if (c<41){
[s appendFormat:@"%c",[@"0123456789" characterAtIndex:c-30]];
} else {
[s appendFormat:@"%c",[@"ABCDEF" characterAtIndex:c-41]];
}
}
return s;
}
@end
int main(int argc, char *argv[]) {
@autoreleasepool {
NSLog(@"%@",[WeirdFormatDecoder decode:@"460046003600430035003900"]); // FF6C59
return EXIT_SUCCESS;
}
}
关于ios - 如何将具有十六进制值的NSString转换为Char- objective-c ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14899399/