print as HEX (0x) or Decimal depending on value without if statements - how to?

208 Views Asked by At

I am trying to print an integer and its formatting should be %d decimal unless its of value FFFF in which case it should be printed as 0xFFFF. I am unable to do so without unnecessary if and else statements. Would it be possible to do this in a single printf statement? Maybe use a macro? Any pointers?

int d;

if(d==0xFFFF) {
    printf("%X",d);
} else {
    printf("%d",d);
}
2

There are 2 best solutions below

11
Fe2O3 On

Code:

int main(void) {

    for( int e = 0xFFFE; e < 0x10002; e++ )
        printf( "%d\n\0%X\n" + ((e == 0xFFFF)<<2), e );

    return 0;
}

Results:

65534
FFFF
65536
65537

You'll recognise the conditional testing the value of the variable. The truth value (0 or 1) is shifted left 2 places, effectively multiplying it by 4. This value (0 or 4) is added to the address of the hacky and custom format string that is actually two C strings in one. Either "%d\n\0" or "%X\n\0" will be used by printf() to print the next parameter.

Now, go read the man page for printf() and work out how to print the hex value with a leading 0x. (Hint: changing "..\0%X.." to "..\00X%x.." will NOT work. Why not?)

Don't write code like this. It's definitely a hack...

0
chqrlie On

You can avoid the if statement with the conditional operator to select the printf statement:

    d == 0xFFFF ? printf("FFFF") : printf("%d", d);

You can combine this into a single call to printf:

    printf(d == 0xFFFF ? "FFFF" : "%d", d);

You can avoid the conditional operator and make the code even more cryptic:

    printf("FFFF\0%d" + (d != 0xFFFF) * 5, d);