objective-cnsstringnsstringencoding

Get a 4 bytes hex string with stringWithFormat


Until now, I have this code :

NSString *hex = [NSString stringWithFormat:@"%lX", crc32Result];

Which formats an int value into a hex (string) value.

But now, I would like to always get a 4 bytes hex with "stringWithFormat". I mean, when the result is, for example : "DFF241", then I would like it to output "00DFF241" instead. If it is "F241", I would like the output to be "0000F241".

Is it possible with "stringWithFormat"?


Solution

  • Yes, it is:

    NSString *hex = [NSString stringWithFormat:@"%08lX", crc32Result];
    

    About the 0 flag:

    For d, i, o, u, x, X, a, A, e, E, f, F, g, and G conversion specifiers, leading zeros (following any indication of sign or base) are used to pad to the field width; no space padding is performed.