简体   繁体   中英

Hex string to hex char[]

I have an integer and want to get hex of this integer in form of char[].

example:

unsigned int i = 1234567890;

and I want to get the following char[]:

char hex[] = "\x49\x96\x02\d2";  // hex of i;

I can get hex as a string:

        std::stringstream sstream;
        sstream << std::hex << image_base_OEP;
        auto result =  sstream.str();

but that's not what I need.

Since you are looking for a null-terminated string of printable and non-printable characters, HEX does not enter into the picture: the four characters in the string are simply the four bytes of i 's representation, which you can get as follows:

char hex[] = {
    (i >> 24) & 0xFF
,   (i >> 16) & 0xFF
,   (i >>  8) & 0xFF
,   (i >>  0) & 0xFF
,   0 // Null terminator to match your C string
};

Note that it is probably a good idea to make i and hex unsigned.

Demo.

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