简体   繁体   中英

int to Hex string (C++)

I have done some research on how to convert an int to Hex string and found an answer , however what i need is a little bit different as you can see in the following code:

    int addr = 5386; // 

    std::string buffer = "contains 0xCCCCCCCC as hex (non ASCII in the string)";
    size_t idx = 0;
    idx = buffer.find("\xCC\xCC\xCC\xCC", idx);
    if (idx != string::npos) buffer.replace(idx, 4, XXX); // here i want to put the addr variable but as 0x0000150A 

What i need is a way to convert the addr variable to a hex string that has the \\x in between the bytes like "\\x0a\\x15\\x00\\x00"

Thanks in advance.

Maybe this program would help you :

#include <sstream>
#include <iomanip>
#include <iostream>

int main(int argc, char const *argv[])
{
    int a = 5386;

    std::ostringstream vStream;
    for(std::size_t i = 0 ; i < 4 ; ++i)
        vStream << "\\x"
                << std::right << std::setfill('0') << std::setw(2) << std::hex
                << ((a >> i*4) & 0xFF);

    std::cout << vStream.str() << std::endl;

    return 0;
}

I am not sure I precisely got your problem, but I understand you want an int to be transformed into a string in format : "\\xAA\\xAA\\xAA\\xAA".

It uses std::right , std::setfill('0') and std::setw(2) to force an output of "2" to be "02". std::hex is to get the hexadecimal representation of a integer.

Something like this:

char buf[20];
uint32_t val;
sprintf(buf, "\\x%02x\\x%02x\\x%02x\\x%02x", 
       (val >> 24), (uint8_t)(val >> 16), (uint8_t)(val >> 8), (uint8_t)val);

You may want to treat addr as char* , but you will have issues with endianness.

you may do the job manually with something like:

unsigned int addr = 5386 // 0x0000150A

char addrAsHex[5] = {(addr >> 24) & 0xFF, (addr >> 16) & 0xFF, (addr >> 8) & 0xFF, addr & 0xFF, 0};

// ...
buffer.replace(idx, 4, addrAsHex);

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