0

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 Answers2

1

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

0___________
  • 60,014
  • 4
  • 34
  • 74
-3

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.

rurban
  • 4,025
  • 24
  • 27
  • Your code will not work. It is a good habit **to test the code before** answering the question. If you do not test - simply do not answer – 0___________ Jan 18 '21 at 23:28