如何以十六进制格式打印 MSB 位等于 0 时

How to print in HEX format the MSBs bits when they're equal to 0

我需要使用 HEX 格式打印变量。 问题是当我的变量很少时,MSB 等于 0,所以它们不会被打印出来。

ex: uint16_t var = 10; // (0x000A)h

-> 我需要打印 "000A" 但无论我做什么它总是只打印 'A'

我怎样才能让它工作?

您可以在宽度说明符中添加前导 0 以强制 printf 添加前导零(至少,您可以在 C 和 C++ 中使用 - 而不是 完全 确定使用该函数的其他语言)。

例如,在 C 中,如下:

#include <stdio.h>
#include <stdint.h>

int main()
{
    uint16_t a = 10; // 0xA
    printf("%04X\n", a);
    //        ^ width specifier: display as 4 digits
    //       ^ this signals to add leading zeros to pad to at least "n" digits
    return 0;
}

将显示:

000A