C++: Hex values to String - c++

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

Related

Reading int with specific field width from stringstream [duplicate]

This question already has an answer here:
setw() does not affect reading integer fields
(1 answer)
Closed 3 years ago.
I'm trying to read bytes in hex notation from a string. The bytes may or may unfortunately not be separated by whitespace, e.g. " 00 ffab c " is a valid example and should result in 4 bytes read, 0x00, 0xff, 0xab and 0x0c. The problem is to skip whitespace but read only two adjacent digits, when present.
If the input were from a file, the task would be as easy as while(fscanf(f, "%2d", &i) == 1) ... because sscanf skips whitespace, the read position is tracked by the underlying FILE, and the maximum field width is only applied to the item read, not the raw input characters containing the whitespace. But the position tracking is not possible when reading from a string; I need to use the %n format conversion specifier which stores the number of characters read so far by this invocation into the associated variable, e.g. scanf(f, "%2d%n", &i, &readIncr), and manually maintain a read position by adding the respective increments.
This is somewhat cumbersome, hence I wanted to use std::istringstream which does keep track of a position in the underlying string.
But setting a width on the input stream does not have the desired (and expected) effect; below is a minimal demonstration; for simplicity I'm using decimal integers. Documentation and examples for an input field width are scarce.
Am I doing something wrong? I this use case simply not intended?
#include <iostream>
#include <sstream>
#include <iomanip>
#include <cstdio>
using namespace std;
int main()
{
const char *s = " 1234";
int i;
istringstream is(s);
if (is >> setw(2) >> i)
{
cout << "stringstream i: " << i << '\n';
}
if (sscanf(s, "%2d", &i) == 1)
{
cout << "scanf i: " << i << '\n';
}
}
The output is (with g++ and MSVC)
$ g++ -Wall -o fieldwidth fieldwidth.cpp && ./fieldwidth
stringstream i: 1234
scanf i: 12
Sadly cpp streams are far from perfect. AFAIK std::setw works only for reading strings. What you can do is:
#include <iostream>
#include <sstream>
#include <iomanip>
#include <cstdio>
using namespace std;
int main()
{
const char *s = " 1234";
std::string i;
istringstream is(s);
if (is >> setw(2) >> i)
{
cout << "stringstream i: " << std::stoi(i) << '\n';
}
int j;
if (sscanf(s, "%2d", &j) == 1)
{
cout << "scanf i: " << j << '\n';
}
}
And you get expected output:
stringstream i: 12
scanf i: 12

how to display char value as string in c++?

So I have a simple char variable which is as follows:
char testChar = 00000;
Now, my goal is to display not the unicode character, but the value itself (which is "00000") in the console. How can I do that? Is it possible to convert it to a string somehow?
To print the char's integer value:
std::cout << static_cast<int>(testChar) << std::endl;
// prints "0"
Without the cast, it calls the operator<< with char argument, which prints the character.
char is an integer type, and only stores the number, not the format ("00000") used in the definition. To print a number with padding:
#include <iomanip>
std::cout << std::setw(5) << std::setfill(' ') << static_cast<int>(testChar) << std::endl;
// prints "00000"
See http://en.cppreference.com/w/cpp/io/manip/setfill .
To convert it to a std::string containing the formatted character number, you can use stringstream:
#include <iomanip>
#include <sstream>
std::ostringstream stream;
stream << std::setw(5) << std::setfill(' ') << static_cast<int>(testChar);
std::string str = stream.str();
// str contains "00000"
See http://en.cppreference.com/w/cpp/io/basic_stringstream .
You are confusing values with representations. The character's value is the number zero. You can express this as "zero", "0", "00", or "1-1" if you want, but it's the same value and it's the same character.
If you want to output the string "0000" if a character's value is zero, you can do it like this:
char a;
if (a==0)
std::cout << "0000";

String as a parameter (C++)

Is this example code valid?
std::string x ="There are";
int butterflies = 5;
//the following function expects a string passed as a parameter
number(x + butterflies + "butterflies");
The main question here is whether I could just pass my integer as part of the string using the + operator. But if there are any other errors there please let me know :)
C++ doesn't do automatic conversion to strings like that. You need to create a stringstream or use something like boost lexical cast.
You can use stringstream for this purpose like that:
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
stringstream st;
string str;
st << 1 << " " << 2 << " " << "And this is string" << endl;
str = st.str();
cout << str;
return 0;
}
A safe way to convert your integers to strings would be an excerpt as follows:
#include <string>
#include <sstream>
std::string intToString(int x)
{
std::string ret;
std::stringstream ss;
ss << x;
ss >> ret;
return ret;
}
Your current example will not work for reasons mentioned above.
No, it wouldn't work. C++ it no a typeless language. So it can't automatically cast integer to string. Use something like strtol, stringstream, etc.
More C than C++, but sprintf (which is like printf, but puts the result in a string) would be useful here.

Splitting C++ Strings Onto Multiple Lines (Code Syntax, Not Parsing)

Not to be confused with how to split a string parsing wise, e.g.:
Split a string in C++?
I am a bit confused as to how to split a string onto multiple lines in c++.
This sounds like a simple question, but take the following example:
#include <iostream>
#include <string>
main() {
//Gives error
std::string my_val ="Hello world, this is an overly long string to have" +
" on just one line";
std::cout << "My Val is : " << my_val << std::endl;
//Gives error
std::string my_val ="Hello world, this is an overly long string to have" &
" on just one line";
std::cout << "My Val is : " << my_val << std::endl;
}
I realize that I could use the std::string append() method, but I was wondering if there was any shorter/more elegant (e.g. more pythonlike, though obviously triple quotes etc. aren't supported in c++) way to break strings in c++ onto multiple lines for sake of readability.
One place where this would be particularly desirable is when you're passing long string literals to a function (for example a sentence).
Don't put anything between the strings. Part of the C++ lexing stage is to combine adjacent string literals (even over newlines and comments) into a single literal.
#include <iostream>
#include <string>
main() {
std::string my_val ="Hello world, this is an overly long string to have"
" on just one line";
std::cout << "My Val is : " << my_val << std::endl;
}
Note that if you want a newline in the literal, you will have to add that yourself:
#include <iostream>
#include <string>
main() {
std::string my_val ="This string gets displayed over\n"
"two lines when sent to cout.";
std::cout << "My Val is : " << my_val << std::endl;
}
If you are wanting to mix a #defined integer constant into the literal, you'll have to use some macros:
#include <iostream>
using namespace std;
#define TWO 2
#define XSTRINGIFY(s) #s
#define STRINGIFY(s) XSTRINGIFY(s)
int main(int argc, char* argv[])
{
std::cout << "abc" // Outputs "abc2DEF"
STRINGIFY(TWO)
"DEF" << endl;
std::cout << "abc" // Outputs "abcTWODEF"
XSTRINGIFY(TWO)
"DEF" << endl;
}
There's some weirdness in there due to the way the stringify processor operator works, so you need two levels of macro to get the actual value of TWO to be made into a string literal.
Are they both literals? Separating two string literals with whitespace is the same as concatenation: "abc" "123" is the same as "abc123". This applies to straight C as well as C++.
I don't know if it is an extension in GCC or if it is standard, but it appears you can continue a string literal by ending the line with a backslash (just as most types of lines can be extended in this manor in C++, e.g. a macro spanning multiple lines).
#include <iostream>
#include <string>
int main ()
{
std::string str = "hello world\
this seems to work";
std::cout << str;
return 0;
}

how to convert a hexadecimal string to a corresponding integer in c++?

i have a unicode mapping stored in a file.
like this line below with tab delimited.
a 0B85 0 0B85
second column is a unicode character. i want to convert that to 0x0B85 which is to be stored in int variable.
how to do it?
You've asked for C++, so here is the canonical C++ solution using streams:
#include <iostream>
int main()
{
int p;
std::cin >> std::hex >> p;
std::cout << "Got " << p << std::endl;
return 0;
}
You can substitute std::cin for a string-stream if that's required in your case.
You could use strtol, which can parse numbers into longs, which you can then assign to your int. strtol can parse numbers with any radix from 2 to 36 (i.e. any radix that can be represented with alphanumeric charaters).
For example:
#include <cstdlib>
using namespace std;
char *token;
...
// assign data from your file to token
...
char *err; // points to location of error, or final '\0' if no error.
int x = strtol(token, &err, 16); // convert hex string to int