print uint32_t to string in C but not it's literally value

1.1k Views Asked by At

I'm reading an image file and I want to show the format it was compressed in console.

In example, I read this: format = 861165636 (0x33545844), as my CPU reads and writes in Little Endian I do format = __builtin_bswap32(format); so now format = 1146639411 (0x44585433), and 0x44585433 = "DXT3" in ASCII.

I want to print this ("DXT3") but not using and extra variable, I mean, something like this printf("Format: %s\n", format); (that obviously crash). There's a way to do it?

2

There are 2 best solutions below

2
0___________ On BEST ANSWER

order paratameter indicates if you want to start from the most significant byte or not.

void printAsChars(uint32_t val, int order)
{   
    if(!order)
    {
        putchar((val >> 0) & 0xff);
        putchar((val >> 8) & 0xff);
        putchar((val >> 16) & 0xff);
        putchar((val >> 24) & 0xff);
    }
    else
    {
        putchar((val >> 24) & 0xff);
        putchar((val >> 16) & 0xff);
        putchar((val >> 8) & 0xff);
        putchar((val >> 0) & 0xff);
    }
}

int main(int argc, char* argv[])
{
    printAsChars(0x44585433,0); putchar('\n');
    printAsChars(0x44585433,1); putchar('\n');
}

https://godbolt.org/z/WWE9Yr

Another option

int main(int argc, char* argv[])
{
    uint32_t val = 0x44585433;
    printf("%.4s", (char *)&val);
}

https://godbolt.org/z/eEj755

1
rurban On

printf("Format: %c%c%c%c\n", format << 24, format << 16, format << 8, format & 256); or something like that. untested. Maybe you need to mask the chars.