Hi I have a string that looks like this:
std::string myString = "123456789";
Is there a way for me to turn that string of a decimal number to a binary number?
Firstly, you want to convert the string representing a number into an actual integer.
As stated by some others: std::stoi "string to int". Depending on the size of the numbers, you may want to use std::stoull. this is the same thing but for long long, a 64 bit integer.
Next you want to convert that number back into string. the easiest thing to use that provides this functionality is std::bitset and its to_string member function. The constructor of bitset requires an unsigned long long, so we'll use std::stoull, the unsigned variant.
This can all be combined into a single line of code:
myString = std::bitset<64>{ std::stoull(myString) }.to_string(); // 64 bits to fit a long long
After this operation, You'll be left with a string that looks like this: 0000000000000000000000000000000000000111010110111100110100010101
You may want to get rid of the zero's up front.
We can use the string's find and erase
myString.erase( 0, myString.find('1') );
This will erase all characters from position 0 until the first 1's position.
If you want to parse string to int, here is how you do it:
std::string strDec = "123456789";
int i = std::stoi(strDec);
If you then want to convert int to string but this time in binary representation, here is a way to do that:
std::string strBin = std::bitset<32>(i).to_string();
Demo
Or, you can use {fmt} library:
#include <fmt/core.h>
int main() {
std::string strDec = "123456789";
std::string strBin = fmt::format("{:032b}", std::stoi(strDec));
}
Demo
Related
Im using this atoi to remove all letters from the string. But my string uses special characters as seen below, because of this my atoi exits with an error. What should I do to solve this?
#include <iostream>
#include <string>
using namespace std;
int main() {
std::string playerPickS = "Klöver 12"; // string with special characters
size_t i = 0;
for (; i < playerPickS.length(); i++) { if (isdigit(playerPickS[i])) break; }
playerPickS = playerPickS.substr(i, playerPickS.length() - i); // convert the remaining text to an integer
cout << atoi(playerPickS.c_str());
}
This is what I believe is the error. I only get this when using those special characters, thats why I think thats my problem.
char can be signed or unsigned, but isidigt without a locale overload expects a positive number (or EOF==-1). In your encoding 'ö' has a negative value. You can cast it to unsigned char first: is_digit(static_cast<unsigned char>(playerPickS[i])) or use the locale-aware variant.
atoi stops scanning when it finds something that's not a digit (roughly speaking). So, to get it to do what you want, you have to feed it something that at least starts with the string you want to convert.
From the documentation:
[atoi] Discards any whitespace characters until the first non-whitespace character is found, then takes as many characters as possible to form a valid integer number representation and converts them to an integer value. The valid integer value consists of the following parts:
(optional) plus or minus sign
numeric digits
So, now you know how atoi works, you can pre-process your string appropriately before passing it in. Good luck!
Edit: If your call to isdigit is failing to yield the desired result, the clue lies here:
The behavior is undefined if the value of ch is not representable as unsigned char and is not equal to EOF.
So you need to check for that yourself before you call it. Casting playerPickS[i] to an unsigned int will probably work.
Suppose I have a string that contains a necessary numeric character but it is not terminated by '/0', it has garbage characters instead. Actually, the string has garbage characters after the number. So how to deal with the garbage character while storing that numerical character in another string or variable?
So how to deal with the garbage character while storing that numerical character in another string or variable?
Only copy a substring. Example:
std::string example "garbage1garbage";
char numerical = example[7];
We got the numerical character excluding the garbage entirely.
If the text be converted is in a std::string, then you can extract a number from the front as follows:
#include <sstream>
...
std::string input = "128734garbage";
std::istringstream iss{input};
int num;
if (iss >> num)
...use_num...
else
std::cerr << "wasn't able to parse an int from input\n";
Just change int to double, uint64_t, ... - whatever suits your data.
If you have only a pointer to the text and know it's not null-terminated, just getting the text into a std::string is problematic. You could instead use a function that converts text to a number, but stops at the first invalid character. std::stol et al, and the other unsigned and floating point variants linked from the same reference page, are good candidates for that.
From your "another string or variable" - the above addresses storing into a numeric variable. You can then create a new std::string from the number using std::to_string, or a std::ostringstream, if that's what you want to do. This will standardise the output format though, so input like say "1E4" might end up looking like say 1000.0. Alternatively, with the stol-type functions you can use the pointer-to-the-end-of-the-number to work out the length of the numeric part, and use std::string::substr() to extract the leading number as a new std::string object.
You should also be aware that the distinction between number and garbage is not always what you might expect. For example "0XBEFHJQ" might be split by some of the above functions as 0xBEF hex and HJQ garbage.
Anyone know how to convert a string to long double? For example lets say we have
string S = "3.236568949"
I want to take what inside the string and convert it to a long double variable x.
Note: In c++11 their exist stold function do so but I'm using c++98 not c++11.
Also I don't need to cout the string with certain precision because I know setprecision function already but what I want is just to convert to long double. In other wards,I need x to equal the exact number inside the string and not an approximated version of the number. Finally I want to tell you that my string contains a valid number.
you can use the C function :
#include <stdlib.h>
int main(){
char* convertme="3.236568949";
double converted=atof(convertme);
return 0;
}
You can use a std::stringstream to convert the string into a long double. The std::stringstream acts just like cin but instead of getting the input from the user you load it into the stream with a std::string. That looks like
std::string data = "3.236568949"
std::stringstream ss(data);
long double ld;
ss >> ld;
Do note that when dealing with floating point numbers you are going to have to deal with imprecision. For more on this see Is floating point math broken?
You can use strtold() function from C99:
long double d = strtold( str.c_str(), nullptr );
to convert std::string to long double. Though floating point representation is approximate so nobody would guarantee that value after conversion is exactly the same is in your string.
I have an array of unsigned chars with hex values and I need to make a string of them. So when I have arr[0]=2b and arr[1]=fc I want to be able to make a string s="2bfc", not the characters from ascii codes. How can I do that?
You could change to long or int and loop through adding +arr[ArrayIndex]*0x10^ArrayIndex to get one int representation of it using itoa(), then convert the int to a literal string of it. Just to outline a manual process of doing it.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to convert a single char into an int
Well, I'm doing a basic program, wich handles some input like:
2+2
So, I need to add 2 + 2.
I did something like:
string mys "2+2";
fir = mys[0];
sec = mys[2];
But now I want to add "fir" to "sec", so I need to convert them to Int.
I tried "int(fir)" but didn't worked.
There are mulitple ways of converting a string to an int.
Solution 1: Using Legacy C functionality
int main()
{
//char hello[5];
//hello = "12345"; --->This wont compile
char hello[] = "12345";
Printf("My number is: %d", atoi(hello));
return 0;
}
Solution 2: Using lexical_cast(Most Appropriate & simplest)
int x = boost::lexical_cast<int>("12345");
Solution 3: Using C++ Streams
std::string hello("123");
std::stringstream str(hello);
int x;
str >> x;
if (!str)
{
// The conversion failed.
}
Alright so first a little backround on why what you attempted didn't work. In your example, fir is declared as a string. When you attempted to do int(fir), which is the same as (int)fir, you attempted a c-style cast from a string to an integer. Essentially you will get garbage because a c-style cast in c++ will run through all of the available casts and take the first one that works. At best your going to get the memory value that represents the character 2, which is dependent upon the character encoding your using (UTF-8, ascii etc...). For instance, if fir contained "2", then you might possibly get 0x32 as your integer value (assuming ascii). You should really never use c-style casts, and the only place where it's really safe to use them are conversions between numeric types.
If your given a string like the one in your example, first you should separate the string into the relevant sequences of characters (tokens) using a function like strtok. In this simple example that would be "2", "+" and "2". Once you've done that you can simple call a function such as atoi on the strings you want converted to integers.
Example:
string str = "2";
int i = atoi(str.c_str()); //value of 2
However, this will get slightly more complicated if you want to be able to handle non-integer numbers as well. In that case, your best bet is to separate on the operand (+ - / * etc), and then do a find on the numeric strings for a decimal point. If you find one you can treat it as a double and use the function atof instead of atoi, and if you don't, just stick with atoi.
Have you tried atoi or boost lexical cast?