简体   繁体   中英

C++: Hex values to String

I would like to convert a hex-value ("206564697374754f") to a string (from hex to ascii). These hex-values are from gdb, so the contents are "reversed" by every two . (So the exact hex-value I need to convert is "4f75747369..."). reverse2() reverses the string appropriately, but it needs to now be converted to hex (hence the "0x", then atoi() ).

The following code is what I have so far, but I run into a runtime-error. What is the issue, and is there a better way of doing this?

#include <bits/stdc++.h> 
using namespace std; 

void reverse2s(string str) 
{ 
for (int i=str.length()-2; i>=0; i-=2) {
    string hx="0x"+str[i]+str[i+1];
    cout << (char)(std::stoi( hx )); 
}
} 

// Driver code 
int main(void) 
{ 
    string s = "206564697374754f"; 
    reverse2s(s); 
    return (0); 
} 

The expression "0x"+str[i]+str[i+1]; does not do what you think. "0x" is a character array (not a string). Since str[i] is a character, the addition will add convert that character to an int, and perform a pointer addition. This results in Undefined Behavior.

To do the string concatenation you're expecting, you need to create a string object first:

string hx="0x"s+str[i]+str[i+1];

"0x"s will create an actual string literal to append characters to.

Well it seems like you're just trying to print it as hex,

so you could do

std::cout << std::hex << 5 << std::endl; // prints 0x5

If you don't care about performance:

std::stringstream s;
s << std::hex << num:
s.str(); // std::string containing your number as hex

If you do care about performance I have no clue

This should work:

#include <iostream>
#include <strstream>
#include <string>

int main()
{
    std::strstream s1; // dynamic buffer
    s1 << std::hex << 12345 << std::endl;
    std::cout << "buffer: '" << s1.str() << "'\n";
    s1.freeze(false);
    return 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