Is there a method that converts string to unsigned int?
_ultoa exists but couldn't find the vise verse version...
std::strtoul() is the one. And then again there are the old ones like atoi().
Boost provides lexical_cast.
#include <boost/lexical_cast.hpp>
[...]
unsigned int x = boost::lexical_cast<unsigned int>(strVal);
Alternatively, you can use a stringstream (which is basically what lexical_cast does under the covers):
#include <sstream>
[...]
std::stringstream s(strVal);
unsigned int x;
s >> x;
sscanf will do what you want.
char* myString = "123"; // Declare a string (c-style)
unsigned int myNumber; // a number, where the answer will go.
sscanf(myString, "%u", &myNumber); // Parse the String into the Number
printf("The number I got was %u\n", myNumber); // Show the number, hopefully 123
It works if you go via _atoi64
unsigned long l = _atoi64(str);
How about int atoi ( const char * str ) ?
string s("123");
unsigned u = (unsigned)atoi(s.c_str());
Related
I would like to convert unsigned char testData[8] = {0xFF,0xF0,0x00,0xA0,0x00,0x00,0x00,0x99};
to a String (Arduino variable type)
Currently I try this:
std::string str( reinterpret_cast<char*>(testData), 8);
// std::string str( testData, testData + sizeof testData / sizeof testData[0] );
String message = String(str.c_str());
But that returns the asci characters of the char values, which makes sense. But what I am trying to achieve is to interpret all the bits(8x8) from the array as a long long (64 bit int) and convert this numerical value to its string representation. I want to achieve this so I can send it in JSON to my nodejs server (which doesnt support 64 bits, so I will probably have to cut in two).
So for instance if I have : {0xFF,0xF0,0x00,0xA0,0x00,0x00,0x00,0x99}
and its long long value for example is: 9894736399534
then I would like to retrieve "9894736399534" in my String object.
As other have pointed out, all you have to do is interpret the raw data as an (unsigned) long long and then store the value in a string, for instance:
#include <iostream>
#include <sstream>
#include <cstdlib>
int main(void)
{
unsigned char testData[8] = {0xFF,0xF0,0x00,0xA0,0x00,0x00,0x00,0x99};
unsigned long long data = *reinterpret_cast<unsigned long long*>(testData);
std::stringstream str;
//str << std::hex << data;
str << data;
std::cout << str.str() << '\n';
return EXIT_SUCCESS;
}
EDIT
The following solution relies on the String constructor to convert the original 64-bit value into 2 32-bit value representations that can either be concatenated or used separately if you need to.
This assumes that the platform is little-endian.
String lsdw = String(*reinterpret_cast<unsigned long*>(&testData[0]), HEX);
String msdw = String(*reinterpret_cast<unsigned long*>(&testData[4]), HEX);
String message = lsdw + msdw;
You first need to reinterpret memory as 64bit int pointer then create a string from the number in that memory region.
So convert the char* to unsigned long long* then dereference it and create a string.
This code should work.
unsigned long long number = *(reinterpret_cast<unsigned long long *>(testData))
std::string stringNum = std::to_string(number);
I think with bitset this can be accomplished easily and here is sample code for the same :
#include <iostream>
#include <sstream>
#include <cstdlib>
#include <bitset>
int main(void)
{
unsigned char testData[8] = {0xFF,0xF0,0x00,0xA0,0x00,0x00,0x00,0x99};
std::cout<<"size of array is "<<sizeof(testData)<<std::endl;
std::stringstream strStream;
for(unsigned int i=0;i<sizeof(testData);i++)
{
std::bitset<16> test(testData[i]);
strStream<<test.to_ullong();
}
std::cout<<"Final string corresponding to this unsigned char array is "<<strStream.str()<<std::endl;
return EXIT_SUCCESS;
}
I gotta question about Ice in C++. One of my methods requires that I pass in a Ice::ByteSeq. I would like to build this ByteSeq from a string. How is this conversion possible?
I tried the options below.
Ice::ByteSeq("bytes") // Invalid conversion to unsigned int
Ice::ByteSeq((byte*)"bytes") // Invalid conversion from byte* to unsigned int
(Ice::ByteSeq)"bytes" // Invalid conversion from const char& to unsigned int
(Ice::ByteSeq)(unsigned int)atoi("bytes") // Blank (obviously, why did I try this?)
How can I make this happen?
EDIT
"bytes" is a placeholder value. My actualy string is non-numeric text information.
Looking at the header, ByteSeq is an alias for vector<Byte>. You can initialise that from a std::string in the usual way
std::string s = "whatever";
Ice::ByteSeq bs(s.begin(), s.end());
or from a string literal with a bit more flappery, such as
template <size_t N>
Ice::ByteSeq byteseq_from_literal(char (&s)[N]) {
return Ice::ByteSeq(s, s+N-1); // assuming you don't want to include the terminator
}
Ice::ByteSeq bs = byteseq_from_literal("whatever");
You were almost there,
Ice::ByteSeq((unsigned int)atoi("bytes"));
should do it
Assuming your Ice::ByteSeq has a constructor that takes unsigned int
To split this down, it's basically doing
int num = atoi("12345"); // num = (int) 12345
unsigned int num2 = (unsigned int)num; // num2 = (unsigned int) 12345
Ice::ByteSeq(num2);
If Ice::ByteSeq is simply a vector of bytes you can convert a string to a vector of bytes by doing a variation of the following:
std::string str = "Hello World";
std::vector<char> bytes(str.begin(), str.end());
The implementation of Ice::Byte is an unsigned char just change the standard code I posted from:
std::vector<char> bytes(str.begin(), str.end());
to
std::vector<unsigned char> bytes(str.begin(), str.end());
and the generated vector should be directly compatible with an Ice::ByteSeq
sample code:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
std::string str = "Hello World";
std::vector<unsigned char> bytes(str.begin(), str.end());
cout << str << endl;
for(int i=0; i < bytes.size(); i++)
std::cout << bytes[i] << '\n';
return 0;
}
Hope this helps:)
I have a question about unsigned ints.
I would like to convert my unsigned int into a char array. For that I use itoa. The problem is that itoa works properly with ints, but not with unsigned int (the unsigned int is treaded as a normal int).
How should I convert unsigned int into a char array?
Thanks in advance for help!
using stringstream is a common approach:
#include<sstream>
...
std::ostringstream oss;
unsigned int u = 598106;
oss << u;
printf("char array=%s\n", oss.str().c_str());
Update since C++11 there is std::to_string() method -:
#include<string>
...
unsigned int u = 0xffffffff;
std::string s = std::to_string(u);
You can simply Make your own function like this one :
Code Link On Ideone using OWN Function
#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
int main()
{
unsigned int num,l,i;
cin>>num;
l = log10(num) + 1; // Length of number like if num=123456 then l=6.
char* ans = new char[l+1];
i = l-1;
while(num>0 && i>=0)
{
ans[i--]=(char)(num%10+48);
num/=10;
}
ans[l]='\0';
cout<<ans<<endl;
delete ans;
return 0;
}
You can also use the sprintf function (standard in C)
sprintf(str, "%d", a); //a is your number ,str will contain your number as string
Code Link On Ideone Using Sprintf
I have a following array and a printf() stament,
char array[1024] = "My Message: 0x7ffff6be9600";
printf("%.14s", strstr(array, " 0x") + 1);
The output of above printf() is 0x7ffff6be9600,
can we store it into a unsigned long variable?
Look at sscanf
Since you tagged this as C++, see istringstream.
using std::istringstream;
const char source_text[] = "0x7ffff6be9600";
unsigned long value;
istringstream input(source_text);
input >> hex >> value;
Try this:
const char* numBuf = strstr(array, " 0x");
unsigned long number = 0; /* Set default value here. */
if(numBuf)
number = strtoul(numBuf + 1, 0, 0);
How do I convert a string into an array of integers? Can I use sstream, because atoi doesn't work?!
As you said in the comments, you got a binary string and you want to convert it into integers. Use bitset for that:
std::istringstream is(str);
std::bitset<32> bits; // assuming each num is 32 bits long
while(is >> bits) {
unsigned long number = bits.to_ulong();
// now, do whatever you want with that long.
v.push_back(number);
}
If you only have one binary number in that string str, you can get away with
unsigned long number = std::bitset<32>(str).to_ulong();
Converting that in C is also possible...
long value;
char const *c = str;
for(;;) {
char * endp;
value = strtol(c, &endp, 2);
if(endp == c)
break;
/* huh, no vector in C. You gotta print it out maybe */
printf("%d\n", value);
c = endp;
}
atoi can't parse binary numbers. But strtol can parse them if you tell it the right base.
How exactly would you like the conversion to work?
Do you simply want an array containing the ASCII value of each character in the array? (so "abc" becomes [97, 98, 99, 0])?
Or do you want to parse the string somehow? ("1, 2, 3" becomes an array [1, 2, 3])
In the first case, in C++, I'd do something like this:
struct convert {
int operator()(char c) {
return static_cast<int>(c);
}
};
std::string str = "hello world";
std::vector<int> result;
std::transform(str.begin(), str.end(), std::back_inserter(result), convert())
Of course you could use a raw array instead of the vector, but since the length of the string is probably going to be variable, and then arrays are just asking for trouble.
If this wasn't what you wanted, you might want to edit your question to be more specific.
From what I understand, for input string "110013" would be converted to array {1,1,0,0,1,3}. Here is how to do it in C++:
string a = "1110011000";
vector<int> v;
for(int i = 0 ; i < a.length() ; i++){
v.push_back(a[i] -'0');
}
// Check the result
for(int i = 0 ; i < v.size() ; i++){
cout << v[i] << endl;
}
Quick string splitter routine:
convert(string str, string delim, vector<int>& results)
{
int next;
char buf[20];
while( (next= str.find_first_of(delim)) != str.npos ) {
if (next> 0)
results.push_back(atoi(str.substr(0,next), buf, 10));
str = str.substr(next+1);
}
if(str.length() > 0)
results.push_back(atoi(str.substr(0,next), buf, 10));
}
You can use stringstream instead of atoi (which does work, on a single int at a time)
int i;
stringstream s (input_string)
s >> i;
If you combine my and jalf's code, you'll get something really good.
Use the istream_iterator in conjunction with a string stream.
By Array I am assuming you really mean a std::vector as you don't know the number of integers at compile time. But the code can easily be modified to use an array rather than a vector.
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>
int main()
{
std::string data = "5 6 7 8 9";
std::vector<int> store;
std::stringstream dataStream(data);
std::copy(std::istream_iterator<int>(dataStream),
std::istream_iterator<int>(),
std::back_inserter(store)
);
// This line just copies the store to the std::cout
// To verify it worked.
std::copy(store.begin(),
store.end(),
std::ostream_iterator<int>(std::cout,",")
);
}
Language: C
Header:
#include <stdlib.h>
Function Prototype:
long int strtol(const char *nptr, char **endptr, int base);
Example Usage:
strtol(nptr, (char **) NULL, 10);