Unsigned int into a char array. Alternative to itoa? - c++

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

Related

Conversion from hexadecimal string to double in C++

I have a string in byte that represent a double number. It is like this in hexadecimal format:
char buffer[17] = "4053E60C49BA5E35";
In double the correct value is: 21,898625.
I need a simple way to convert this string in double. The only way that work just now is this, but I'm not sure it this the best way:
double hexstr2double(const std::string& hexstr)
{
union
{
long long i;
double d;
} value;
try{
value.i = std::stoll(hexstr, nullptr, 16);
}
catch(...){value.i=0;}
return value.d;
}
Thank you
You can use reinterpret_cast instead of the union.
Also the value you presented is different on a site for conversion from hex to double: https://gregstoll.com/~gregstoll/floattohex/
#include <iostream>
using namespace std;
double hexstr2double(const std::string& hexstr)
{
double d = 0.0;
try{
*reinterpret_cast<unsigned long long*>(&d) = std::stoull(hexstr, nullptr, 16);
}
catch(...){}
return d;
}
int main()
{
char buffer[] = "4035e60c49ba5e35";
cout<<sizeof(double)<<" "<<sizeof(unsigned long long)<<endl;
cout<<hexstr2double(buffer);
return 0;
}

any alternative of itoa converting integer in base 2 to string?

as we know itoa tries to convert an integer in any base but to char array which has fix size, I am trying to find an alternative which can do the same work but convert to string with base 2 in c++.
You can easily write your own.
void my_itoa(int value, std::string& buf, int base){
int i = 30;
buf = "";
for(; value && i ; --i, value /= base) buf = "0123456789abcdef"[value % base] + buf;
}
This was taken from this website, along with many other alternatives.
For C++11, you can use bitset and to_string.
#include <iostream>
#include <bitset>
using namespace std;
int main() {
// your code goes here
cout << bitset<4>(10).to_string() << endl;
return 0;
}

Conversion from string to Ice::ByteSeq

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:)

how to convert ascii to unsigned int

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());

How do I convert a string in C++ or C to an integer array?

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