This question already has answers here:
C++ convert hex string to signed integer
(10 answers)
Closed 8 years ago.
I have searched online, but it doesn't seem to be a solution to my problem. Basically I have a std::string which contains a hexadecimal memory address (like 0x10FD7F04, for example). This number is read from a text file and saved as a std::string, obviously.
I need to convert this string to an int value, but keeping the hex notation, 0x. Is there any way to do this?
You can use C++11 std::stoi function:
#include <iostream>
#include <iomanip>
#include <string>
int main()
{
std::string your_string_rep{"0x10FD7F04"};
int int_rep = stoi(your_string_rep, 0, 16);
std::cout << int_rep << '\n';
std::cout << std::hex << std::showbase << int_rep << '\n';
}
Outputs:
285048580
0x10fd7f04
I need to convert this string to an int value, but keeping the hex notation, 0x. Is there any way to do this?
There are two parts to your question:
Convert the string hexadecimal representation to an integer.
std::string your_string_rep{ "0x10FD7F04" };
std::istringstream buffer{ your_string_rep };
int value = 0;
buffer >> std::hex >> value;
Keeping the hex notation on the resulting value. This is not necessary/possible, because an int is already a hexadecimal value (and a decimal value and a binary value, depending on how you interpret it).
In other words, with the code above, you can just write:
assert(value == 0x10FD7F04); // will evaluate to true (assertion passes)
Alternatively you can use something like this
std::string hexstring("0x10FD7F04");
int num;
sscanf( hexstring.data(), "%x", &num);
Related
This question already has an answer here:
Inlining the UnrealEngine UE_LOG macro with C++
(1 answer)
Closed 9 months ago.
I am following a tutorial in which they use BIO_printf(bio_out,"%02x",bs->data[i] ); in order to get the characters of a serial number stored in bs->data (which is an array of unsigned char) and they use "%02x" to specify the format of the char. I am using c++ and I want to add each of these chars to a stringstream but I can't find a way to translate the format and instead of a serial number I get ጄ냾�㮚㭖嵺ﭔ촋ᙰ.
I have tried using
std::stringstream serial("Serial: ");
for (int i = 0; i < bs->length; i++)
{
serial << std::setw(2) << std::hex << bs->data[i] << std::endl;
}
but I still don't get a valid string, and
char* buffer = const_cast<char*>(serial.str().c_str());
sprintf(buffer, "%02x", bs->data[i]);
doesn't seem to work either (don't mind the const cast, I know it is bad practice)
You can use a combination of the std::setw(), std::setfill() and std::hex manipulators to set the width and fill characters. Also, you need to explicitly cast a char variable to an int in order to get the numerical representation, otherwise the << operator (on a char) will output (or attempt to output) the represented character.
Here's a short example using the std::cout stream (though the manipulators work in the same way on a std::stringstream object):
#include <iostream>
#include <iomanip>
int main()
{
char c = 13;
std::cout << std::setfill('0') << std::setw(2) << std::hex << static_cast<int>(c) << std::endl; // Shows 0d
return 0;
}
In c++,
I don't understand about this experience. I need your help.
in this topic, answers saying use to_string.
but they say 'to_string' is converting bitset to string and cpp reference do too.
So, I wonder the way converting something data(char or string (maybe ASCII, can convert unicode?).
{It means the statement can be divided bit and can be processed it}
The question "How to convert char to bits?"
then answers say "use to_string in bitset"
and I want to get each bit of my input.
Can I cleave and analyze bits of many types and process them? If I can this, how to?
#include <iostream>
#include <bitset>
#include <string>
using namespace std;
int main() {
char letter;
cout << "letter: " << endl;
cin >> letter;
cout << bitset<8>(letter).to_string() << endl;
bitset<8> letterbit(letter);
int lettertest[8];
for (int i = 0; i < 8; ++i) {
lettertest[i] = letterbit.test(i);
}
cout << "letter bit: ";
for (int i = 0; i < 8; ++i) {
cout << lettertest[i];
}
cout << endl;
int test = letterbit.test(0);
}
When executing this code, I get result I want.
But I don't understand 'to_string'.
An important point is using of "to_string"
{to_string is function converting bitset to string(including in name),
then Is there function converting string to bitset???
Actually, in my code, use the function with a letter -> convert string to bitset(at fitst, it is result I want)}
help me understand this action.
Q: What is a bitset?
https://www.cplusplus.com/reference/bitset/bitset/
A bitset stores bits (elements with only two possible values: 0 or 1,
true or false, ...).
The class emulates an array of bool elements, but optimized for space
allocation: generally, each element occupies only one bit (which, on
most systems, is eight times less than the smallest elemental type:
char).
In other words, a "bitset" is a binary object (like an "int", a "char", a "double", etc.).
Q: What is bitset<>.to_string()?
Bitsets have the feature of being able to be constructed from and
converted to both integer values and binary strings (see its
constructor and members to_ulong and to_string). They can also be
directly inserted and extracted from streams in binary format (see
applicable operators).
In other words, to_string() allows you to convert the binary bitset to text.
Q: How to to I convert convert char(or string, other type) -> bits?
A: Per the above, simply use bitset<>.to_ulong()
Here is an example:
https://en.cppreference.com/w/cpp/utility/bitset/to_string
Code:
#include <iostream>
#include <bitset>
int main()
{
std::bitset<8> b(42);
std::cout << b.to_string() << '\n'
<< b.to_string('*') << '\n'
<< b.to_string('O', 'X') << '\n';
}
Output:
00101010
**1*1*1*
OOXOXOXO
This question already has answers here:
Integer to hex string in C++
(27 answers)
Closed 5 years ago.
I have an int which I want to convert to a char array, but I want the char array to be formatted in hexadecimal and with every byte of the int taking up exactly 2 char variables (filled out with zeroes).
To clarify what I mean, I have an example:
I want the int 232198 (0x38b06) to become "00038b06".
I can of course acomplish this by using this code:
#include <iostream>
#include <iomanip>
int main()
{
std::cout <<
std::hex <<
std::setw(8) <<
std::setfill('0') <<
232198 <<
std::endl;
return 0;
}
Which prints out:
00038b06
But that only prints it out to the console, and as I mentioned before, want to store it a char array.
I don't care if the code is portable or not, this just has to work for windows.
stringstreams are useful to do this:
std::stringstream sstr;
sstr <<
std::hex <<
std::setw(8) <<
std::setfill('0') <<
232198;
std::string str = sstr.str();
now str contains the formatted number. str.c_str() will give you a const char*.
Is there a simple way to convert a binary bitset to hexadecimal? The function will be used in a CRC class and will only be used for standard output.
I've thought about using to_ulong() to convert the bitset to a integer, then converting the integers 10 - 15 to A - F using a switch case. However, I'm looking for something a little simpler.
I found this code on the internet:
#include <iostream>
#include <string>
#include <bitset>
using namespace std;
int main(){
string binary_str("11001111");
bitset<8> set(binary_str);
cout << hex << set.to_ulong() << endl;
}
It works great, but I need to store the output in a variable then return it to the function call rather than send it directly to standard out.
I've tried to alter the code but keep running into errors. Is there a way to change the code to store the hex value in a variable? Or, if there's a better way to do this please let me know.
Thank you.
You can send the output to a std::stringstream, and then return the resultant string to the caller:
stringstream res;
res << hex << uppercase << set.to_ulong();
return res.str();
This would produce a result of type std::string.
Here is an alternative for C:
unsigned int bintohex(char *digits){
unsigned int res=0;
while(*digits)
res = (res<<1)|(*digits++ -'0');
return res;
}
//...
unsigned int myint=bintohex("11001111");
//store value as an int
printf("%X\n",bintohex("11001111"));
//prints hex formatted output to stdout
//just use sprintf or snprintf similarly to store the hex string
Here is the easy alternative for C++:
bitset <32> data;
/*Perform operation on data*/
cout << "data = " << hex << data.to_ulong() << endl;
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C++ convert hex string to signed integer
I have the string line which is a hexadecimal number say like 12ab43c..(but I have read it as a string) and I would like to pass it to an unsigned char* linehex or directly to a hexadecimal so I can later use it in my program for further computations.
Which is the most efficient way to do this?
The easiest is probably to read it as a number to start with, instead of reading it as a string, then converting. For example:
some_stream >> std::hex >> your_number;
Quick demo code:
#include <iostream>
int main() {
int x;
std::cin >> std::hex >> x;
std::cout << x << "\n";
return 0;
}
Input: ff
Output: 255