将uint32_t打印到 C 中的字符串,但不是字面值



我正在读取一个图像文件,我想在控制台中显示它被压缩的格式。

例如,我读到:format = 861165636 (0x33545844),当我的CPU在Little Endian中读写时,我读format = __builtin_bswap32(format);,现在读format = 1146639411 (0x44585433),用ASCII写0x44585433 = "DXT3"

我想打印这个("DXT3"),但不使用和额外的变量,我的意思是,像这个printf("Format: %sn", format);(显然崩溃了)。有办法吗?

order参数指示是否从最高有效字节开始。

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

另一种选择

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

https://godbolt.org/z/eEj755

printf("Format: %c%c%c%cn", format << 24, format << 16, format << 8, format & 256);或者类似的东西。未经测试。也许你需要掩盖字符。

最新更新