简体   繁体   中英

Convert uint32 address into char array

I would like to convert a uint32 to a char string for printing purposes. My uint32 is an address that looks something like " 0x00402B00 "

I could care less about the preceding " 0x ", but it doesn't matter if it's in there.

How can I turn this number into a char string where:

string[0] = 0
string[1] = 0
string[2] = 4
string[3] = 0
string[4] = 2

....and so on.

Will something like this work?:

uint32 address = 0x00402b00;
char string[8];

sprintf(string, '%u', address);

Any ideas?

Three things:

  1. The char array needs to have room for a terminating NUL, so it should be at least 9 elements (not 8).
  2. The sprintf format string argument needs to be a double-quoted string literal (not a single-quoted character literal).
  3. A format string of %08x will ensure an 8-digit, leading-zero-padded, hex result ( %u is an un-padded decimal).

The code should be:

uint32 address = 0x00402b00;
char string[9];
sprintf(string, "%08x", address);

Using the "x" conversion specifier from printf (or sprintf) should do the trick.

You can omit the "0x" part if you don't want the 0x portion.

Code:

#include <cstdio>

int main() {
    unsigned int address = 0xDEADBEEF;

    printf("Lowercase: 0x%x\n", address);
    printf("Uppercase: 0x%X\n", address);

    return 0;
}

Output:

g++ -O2 -Wall -pedantic -pthread test.cpp && ./a.out

Lowercase: 0xdeadbeef
Uppercase: 0xDEADBEEF

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