【问题标题】:How to print in HEX format the MSBs bits when they're equal to 0当 MSB 位等于 0 时如何以 HEX 格式打印
【发布时间】:2021-05-22 09:12:52
【问题描述】:

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

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

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

我怎样才能让它工作?

【问题讨论】:

    标签: c hex printf


    【解决方案1】:

    您可以在宽度说明符中添加前导 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
    

    【讨论】:

      猜你喜欢
      • 2021-01-23
      • 2020-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-15
      • 2018-02-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多