0

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); } 
2
  • 1
    It looks like you START with the value as an ascii string, right? Start with "0x". Reverse-iterate through the string, every two characters are combined with the "0x". Push this constructed string into a std::vector<std::string> one_byte_hex;, call it done Commented Mar 9, 2020 at 15:44
  • 6
    Recommended reading: Why should I not #include <bits/stdc++.h>? Commented Mar 9, 2020 at 15:47

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

s/string literal/std::string literal/ ;)
0

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

1 Comment

Then I need to convert that to a string (in ascii).
0

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; } 

8 Comments

Blimey, std::strstream
@AsteroidsWithWings care to elaborate??
Well only that I haven't seen it used in a long time and it was deprecated over 20 years ago. I'm not necessarily saying "don't use it" (I actually personally think it's underrated!), but I'm wondering why you chose it over std::stringstream
@AsteroidsWithWings I have never used any of those. strstream was shorter to type =)
|