0

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.

Community
  • 1
  • 1
Hanan
  • 1,169
  • 3
  • 23
  • 40
  • did you take a look at http://stackoverflow.com/questions/15823597/use-printf-to-print-character-string-in-hex-format-distorted-results ? – Thomas Sep 30 '13 at 14:04
  • 2
    The buffer contains eight char 'C' (0x43) but you search for the char (0xCC). This will not match. What do you want to achieve? – harper Sep 30 '13 at 14:07
  • @harper nope, as i wrote the buffer actually contains 4 bytes as `cc:cc:cc:cc` – Hanan Sep 30 '13 at 14:14
  • Your source code has 8 characters "CCCCCCCC". It's a hard job to fold this into four bytes. – harper Sep 30 '13 at 14:24
  • http://stackoverflow.com/questions/5100718/int-to-hex-string-in-c provides a good and simple answer using – fhahn Apr 30 '14 at 08:38

3 Answers3

2

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.

Oragon Efreet
  • 1,114
  • 1
  • 8
  • 25
1

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);
olegarch
  • 3,670
  • 1
  • 20
  • 19
1

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);
Jarod42
  • 203,559
  • 14
  • 181
  • 302