【问题标题】:Hex to human readable NSString十六进制到人类可读的 NSString
【发布时间】:2014-11-01 03:39:22
【问题描述】:

我有这样的输出:

63006f00 6c006f00 72000000

这个输出的意思是“颜色”,但如何在可可中获得它?

我在 Stackoverflow 上也找到了这种方法:

- (NSString *)hexToString:(NSString *)string {
NSMutableString * newString = [[NSMutableString alloc] init];
NSScanner *scanner = [[NSScanner alloc] initWithString:string];
unsigned value;
while([scanner scanHexInt:&value]) {
    [newString appendFormat:@"%c",(char)(value & 0xFF)];
}
string = [newString copy];
return string;

}

它工作......但我的字符串必须如下:

@"63 00 6f 00 6c 00 6f 00 72 00 00 00"

对上面的字符串格式有帮助吗?

【问题讨论】:

    标签: objective-c macos cocoa hex


    【解决方案1】:

    您可以更改代码以使用原始输入,如下所示:

    NSString *string = @"0x63006f00 0x6c006f00 0x72000000";
    NSMutableString * newString = [[NSMutableString alloc] init];
    NSScanner *scanner = [[NSScanner alloc] initWithString:string];
    unsigned value;
    while([scanner scanHexInt:&value]) {
        uint16_t a = (value >> 24) & 0xff;
        uint16_t b = (value >> 8) & 0xff;
        if (a) [newString appendFormat:@"%c", a];
        if (b) [newString appendFormat:@"%c", b];
    }
    NSLog(@"%@", newString);
    

    这个想法是一次处理两个字符,并在用0xff掩盖它们之前将相应的项目移动到适当的位置。

    但是,这看起来很像读取以 UTF-16 编码的内容的解决方法。

    【讨论】:

    • 是的,这是一种解决方法,但它可以工作..稍作调整: NSString*string = [[NSString stringWithFormat:@"0x%@", @"63006f00 6c006f00 72000000"] stringByReplacingOccurrencesOfString:@" " withString:@"0x"];谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-30
    • 1970-01-01
    • 2015-04-06
    • 1970-01-01
    • 2017-04-03
    • 1970-01-01
    相关资源
    最近更新 更多