将NSNumber转换为16位的十六进制字符串

时间:2013-11-24 21:15:29

标签: iphone objective-c macos cocoa nsstring

我必须将NSNumber转换为十六进制字符串,如下所示:

return [NSString stringWithFormat:@"%llX", self.unsignedLongLongValue];

不幸的是,这有时会给我93728A166D1A287这样的字符串,它们应该是093728A166D1A287,具体取决于数字。

提示:领先 0


我也尝试过:

return [NSString stringWithFormat:@"%16.llX", self.unsignedLongLongValue];

没有成功。


我可以做这样的事情,但这很糟糕:

- (NSString *)hexValue {
    NSString *hex = [NSString stringWithFormat:@"%llX", self.unsignedLongLongValue];
    NSUInteger digitsLeft = 16 - hex.length;

    if (digitsLeft > 0) {
        NSMutableString *zeros = [[NSMutableString alloc] init];
        for (int i = 0; i < digitsLeft; i++) [zeros appendString:@"0"];
        hex = [zeros stringByAppendingString:hex];
    }

    return hex;
}

最后我的问题是,有没有办法将字符串强制为16个字符?

2 个答案:

答案 0 :(得分:6)

如果您需要填充十六进制数字,请在格式说明符前面使用零,如下所示:

return [NSString stringWithFormat:@"%016llX", self.unsignedLongLongValue];

这应该注意用16位数字格式化您的号码,无论有多少&#34;有意义的&#34;数字有的数字。

这是普通C中的a demo of this format string(这部分在两种语言之间共享)。

答案 1 :(得分:3)

使用:

return [NSString stringWithFormat:@"%016llX", self.unsignedLongLongValue];

设置前导0和输出字符串的长度。

相关问题