简体   繁体   中英

How to print hex from uint32_t?

The code I have been working on requires that I print a variable of type uint32_t in hexadecimal, with a padding of 0s and minimum length 8. The code I have been using to do this so far is:

printf("%08lx\n",read_word(address));

Where read_word returns type uint32_t. I have used jx, llx, etc. formats to no avail, is there a correct format that can be used?

EDIT:

I have found the problem lies in what I am passing. The function read_word is returns a value from a uint32_t vector. It seems that this is the problem that is causing problems with out putting hex. Is this a passing by reference/value issue and what is the fix?

read_word function:

uint32_t memory::read_word (uint32_t address) {
  if(address>(maxWord)){
        return 0;
    }

    return mem[address];

}

mem deceleration:

std::vector<uint32_t> mem=decltype(mem)(1024,0);

To do this in C++ you need to abuse both the fill and the width manipulators:

#include <iostream>
#include <iomanip>
#include <cstdint>

int main()
{
    uint32_t myInt = 123456;
    std::cout << std::setfill('0') << std::setw(8) << std::hex << myInt << '\n';
}

Output

0001e240

For C it gets a little more obtuse. You use inttypes.h

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


int main()
{
    uint32_t myInt = 123456;
    printf("%08" PRIx32 "\n", myInt);
    return 0;
}

Output

0001e240

Note that in C, the constants from inttypes.h are used with the language string-concatenation feature to form the required format specifier. You only provide the zero-fill and minimum length as a preamble.

%jx + typecast

I think this is correct:

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

int main(void) {
    uint32_t i = 0x123456;
    printf("%08jx\n", (uintmax_t)i);
    return 0;
}

compile and run:

gcc -Wall -Wextra -pedantic -std=c99 main.c
./a.out

Output:

00123456

Let me know if you can produce a failing test case.

Tested in Ubuntu 16.04, GCC 6.4.0.

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