简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM