IluTov
IluTov

Reputation: 6852

Convert NSNumber to hex string with 16 digits

I have to convert an NSNumber to a hex string like follows:

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

Unfortunately, this will sometimes give me string like 93728A166D1A287 where they should be 093728A166D1A287, depending on the number.

Hint: the leading 0.


I've also tried it with:

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

without success.


I could do something like this, but that just sucks:

- (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;
}

So finally my question, is there a way to enforce the string to be 16 characters?

Upvotes: 2

Views: 4776

Answers (2)

trojanfoe
trojanfoe

Reputation: 122381

Use:

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

Which sets leading 0 and the length of the output string.

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

If you need to zero-pad your hex numbers, use zero in front of the format specifier, like this:

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

This should take care of formatting your number with 16 digits, regardless of how many "meaningful" digits the number has.

Here is a demo of this format string in plain C (this part is shared between the two languages).

Upvotes: 8

Related Questions