Search code examples
cstringprintinghexuint32-t

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


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?


Solution

  • 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