ScaryTyss
ScaryTyss

Reputation: 13

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

I need to print variables using HEX format. The problem is when my variables are little the MSBs equal 0 so they are not printed.

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

-> I need to print "000A" but no matter what I do it always prints just 'A'

How could I get it to work?

Upvotes: 1

Views: 264

Answers (1)

Adrian Mole
Adrian Mole

Reputation: 51874

You can add a leading 0 to the width specifier in order to force printf to add leading zeros (at least, you can in C and C++ - not entirely sure about other languages that use the function).

For example, in C, the following:

#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;
}

will display:

000A

Upvotes: 1

Related Questions