I have a string which is as shown below.
std::string myString = "0005105C9A84BE03";
I want the exact data to be saved on some integer say "long long int"
long long int myVar = 0005105C9A84BE03;
When i print myVar i'm expecting output 1425364798979587.
I tried to use atoi, strtol stroi, strtoll but nothing worked out for me.
Any idea how to solve it?
The following should work:
#include <iostream>
#include <sstream>
int main()
{
std::string hexValue = "0005105C9A84BE03"; // Original string
std::istringstream converter { hexValue }; // Or ( ) for Pre-C++11
long long int value = 0; // Variable to hold the new value
converter >> std::hex >> value; // Extract the hex value
std::cout << value << "\n";
}
This code uses an std::istringstream to convert from std::string to long long int, through the usage of the std::hex stream manipulator.
Example
There is a list of functions to convert from string to different integer types like:
stol Convert string to long int (function template )
stoul Convert string to unsigned integer (function template )
strtol Convert string to long integer (function )
They are some more. Please take a look at http://www.cplusplus.com/reference/string/stoul At the end of the documentation you find alternative functions for different data types.
All they have a "base" parameter. To convert from hex simply set base=16.
std::cout << std::stoul ("0005105C9A84BE03", 0, 16) << std::endl;
Related
In c++
I have an array of signed long long (63bit numbers), array of variable lenght.
std::array<long long, n> encodedString
This array is in fact holding an UTF-8 encoded string. Meaning that if you concatenate the binaries of each element of the array, the result will be an UTF-8 encoded text.
For example the array :
(621878499550 , 2339461068677718049)
If you translate those signed long long in 63 bit binary it gives :
621878499550 = 000000000000000000000001001000011001010110110001101100011011110
2339461068677718049 = 010000001110111011011110111001001101100011001000010000000100001
If you concatenate those binaries into :
000000000000000000000001001000011001010110110001101100011011110010000001110111011011110111001001101100011001000010000000100001
This is the UTF8 for "Hello world !"
So the question is what is the easiest way to get a string with "Hello world !" starting with the array (621878499550 , 2339461068677718049)
Best solution I currently have is to write the array to a file in binary mode (fwrite) then read the file in text mode to a string.
Use bitset to convert a long long to binary and string stream to stream them
#include <sstream>
#include <iostream>
#include <bitset>
#include <array>
int main()
{
std::array<long long, 2> array = { 621878499550 , 2339461068677718049ll };
std::stringstream ss;
for (auto& n : array)
{
ss << std::bitset<64>(n);
}
std::cout << ss.str() << std::endl;
}
which outputs 0000000000000000000000010010000110010101101100011011000110111100010000001110111011011110111001001101100011001000010000000100001
Try this
// 48 & 56 were to avoid the extra padding made when you use 64 bitset but i think thats what you are looking for
std::string binary = std::bitset<48>(114784820031264).to_string();
std::string binary2 = std::bitset<56>(2339461068677718049).to_string();
binary += binary2;
std::stringstream sstream(binary);
std::string output;
while (sstream.good())
{
std::bitset<8> bits;
sstream >> bits;
output +=char(bits.to_ulong());
}
std::cout << output;
Based on my previous question
C++: Convert hex representation of UTF16 char into decimal (like python's int(hex_data, 16))
I would like to know how to convert a string into unicode for char16_t:
As
int main()
{
char16_t c = u'\u0b7f';
std::cout << (int)c << std::endl;
return 0;
}
yields decimal 2943 perfectly fine, I now need to know how to inject a 4-digit string into char16_t c = u'\uINSERTHERE'
My stringstream_s contains 4 hex representation letters like '0b82' (decimal: 2946) or '0b77' (decimal: 2935).
I tried
std::string stringstream_s;
....stringstream_s gets assigned....
char16_t c = (u'\u%s',stringstream_s);
and it gives me "no suitable conversion function from std::string to char16_t exists"
So basically speaking, how to convert a string into unicode utf16.....?
I need to know the equivalent of u'\u0b7f' when I just have a bare string of '0b7f'
You need to convert the std::string to an integer first, then you can type-cast the integer to char16_t. In this case, std::stoi() would be the simplest solution:
std::string s = "0b82";
char16_t ch = (char16_t) std::stoi(s, nullptr, 16);
Alternatively, you can use a std::istringstream instead:
std::string s = "0b82";
unsigned short i;
std::istringstream(s) >> std::hex >> i;
char16_t ch = (char16_t) i;
I have a string which actually contains a number and a string, separated by ,, for instance "12,fooBar".
I would like to put it into separated variables, i.e. the number into unsigned int myNum and the string into std::string myStr.
I have the following snipped of code:
size_t pos1=value.find(',');
std::cout << value.substr(0, pos1) << " and "
<< (value.substr(0, pos1)).c_str() << std::endl;
This yields 12 and 1. Anything I missed here? What happend to the 2 in the second part?
Note: I isolated the problem to this snipped of code. I need c_str() to pass it to atoi to get the unsigend int. Here I don't want to print the second part.
Update: I actually get the string from levelDB Get. If I put a test string like I put here, it works.
The posted code produces the same substring: value.substr(0, pos1). Note that std::string::substr() does not modify the object, but returns a new std::string.
Example:
#include <iostream>
#include <string>
int main ()
{
std::string value ="12,fooBar";
unsigned int myNum;
std::string myStr;
const size_t pos1 = value.find(',');
if (std::string::npos != pos1)
{
myNum = atoi(value.substr(0, pos1).c_str());
myStr = value.substr(pos1 + 1);
}
std::cout << myNum << " and "
<< myStr << std::endl;
return 0;
}
Output:
12 and fooBar
EDIT:
If the unsigned int is the only piece required then the following will work:
unsigned int myNum = atoi(value.c_str());
as atoi() will stop at the first non-digit character (excluding optional leading - or +), in this case the ,.
The cleanest C++ style solution to this problem is to use a stringstream.
#include <sstream>
// ...
std::string value = "12,fooBar";
unsigned int myNum;
std::string myStr;
std::stringstream myStream(value);
myStream >> myNum;
myStream.ignore();
myStream >> myStr;
Your second substr should be value.substr(pos1+1,value.length())
One more option is using std::from_chars function from the 17th standard (< charconv > header):
int x;
from_chars(&s[i], &s.back(), x); // starting from character at index i parse
// the nearest interger till the second char pointer
There are different overloads for different types of value x (double etc.).
Usually when I write anything in C++ and I need to convert a char into an int I simply make a new int equal to the char.
I used the code(snippet)
string word;
openfile >> word;
double lol=word;
I receive the error that
Code1.cpp cannot convert `std::string' to `double' in initialization
What does the error mean exactly? The first word is the number 50. Thanks :)
You can convert char to int and viceversa easily because for the machine an int and a char are the same, 8 bits, the only difference comes when they have to be shown in screen, if the number is 65 and is saved as a char, then it will show 'A', if it's saved as a int it will show 65.
With other types things change, because they are stored differently in memory. There's standard function in C that allows you to convert from string to double easily, it's atof. (You need to include stdlib.h)
#include <stdlib.h>
int main()
{
string word;
openfile >> word;
double lol = atof(word.c_str()); /*c_str is needed to convert string to const char*
previously (the function requires it)*/
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << stod(" 99.999 ") << endl;
}
Output: 99.999 (which is double, whitespace was automatically stripped)
Since C++11 converting string to floating-point values (like double) is available with functions:
stof - convert str to a float
stod - convert str to a double
stold - convert str to a long double
As conversion of string to int was also mentioned in the question, there are the following functions in C++11:
stoi - convert str to an int
stol - convert str to a long
stoul - convert str to an unsigned long
stoll - convert str to a long long
stoull - convert str to an unsigned long long
The problem is that C++ is a statically-typed language, meaning that if something is declared as a string, it's a string, and if something is declared as a double, it's a double. Unlike other languages like JavaScript or PHP, there is no way to automatically convert from a string to a numeric value because the conversion might not be well-defined. For example, if you try converting the string "Hi there!" to a double, there's no meaningful conversion. Sure, you could just set the double to 0.0 or NaN, but this would almost certainly be masking the fact that there's a problem in the code.
To fix this, don't buffer the file contents into a string. Instead, just read directly into the double:
double lol;
openfile >> lol;
This reads the value directly as a real number, and if an error occurs will cause the stream's .fail() method to return true. For example:
double lol;
openfile >> lol;
if (openfile.fail()) {
cout << "Couldn't read a double from the file." << endl;
}
If you are reading from a file then you should hear the advice given and just put it into a double.
On the other hand, if you do have, say, a string you could use boost's lexical_cast.
Here is a (very simple) example:
int Foo(std::string anInt)
{
return lexical_cast<int>(anInt);
}
The C++ way of solving conversions (not the classical C) is illustrated with the program below. Note that the intent is to be able to use the same formatting facilities offered by iostream like precision, fill character, padding, hex, and the manipulators, etcetera.
Compile and run this program, then study it. It is simple
#include "iostream"
#include "iomanip"
#include "sstream"
using namespace std;
int main()
{
// Converting the content of a char array or a string to a double variable
double d;
string S;
S = "4.5";
istringstream(S) >> d;
cout << "\nThe value of the double variable d is " << d << endl;
istringstream("9.87654") >> d;
cout << "\nNow the value of the double variable d is " << d << endl;
// Converting a double to string with formatting restrictions
double D=3.771234567;
ostringstream Q;
Q.fill('#');
Q << "<<<" << setprecision(6) << setw(20) << D << ">>>";
S = Q.str(); // formatted converted double is now in string
cout << "\nThe value of the string variable S is " << S << endl;
return 0;
}
Prof. Martinez
Coversion from string to double can be achieved by
using the 'strtod()' function from the library 'stdlib.h'
#include <iostream>
#include <stdlib.h>
int main ()
{
std::string data="20.9";
double value = strtod(data.c_str(), NULL);
std::cout<<value<<'\n';
return 0;
}
#include <string>
#include <cmath>
double _string_to_double(std::string s,unsigned short radix){
double n = 0;
for (unsigned short x = s.size(), y = 0;x>0;)
if(!(s[--x] ^ '.')) // if is equal
n/=pow(10,s.size()-1-x), y+= s.size()-x;
else
n+=( (s[x]-48) * pow(10,s.size()-1-x - y) );
return n;
}
or
//In case you want to convert from different bases.
#include <string>
#include <iostream>
#include <cmath>
double _string_to_double(std::string s,unsigned short radix){
double n = 0;
for (unsigned short x = s.size(), y = 0;x>0;)
if(!(s[--x] ^ '.'))
n/=pow(radix,s.size()-1-x), y+= s.size()-x;
else
n+=( (s[x]- (s[x]<='9' ? '0':'0'+7) ) * pow(radix,s.size()-1-x - y) );
return n;
}
int main(){
std::cout<<_string_to_double("10.A",16)<<std::endl;//Prints 16.625
std::cout<<_string_to_double("1001.1",2)<<std::endl;//Prints 9.5
std::cout<<_string_to_double("123.4",10)<<std::endl;//Prints 123.4
return 0;
}
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