C++ convert binary to decimal from string input - c++

I have a problem because i have string input and i want to convert it to decimal.
Here's my code :
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
string inputChecker;
int penghitung =0;
int main(){
string source = "10010101001011110101010001";
cout <<"Program Brute Force \n";
cout << "Masukkan inputan : ";
cin >> inputChecker;
int pos =inputChecker.size();
for (int i=0;i<source.size();i++){
if (source.substr(i,pos)==inputChecker){
penghitung +=1;
}
}
if (source.find(inputChecker) != string::npos)
cout <<"\nData " << inputChecker << " ada pada source\n";
else
cout <<"\nData "<< inputChecker <<" tidak ada pada source\n";
cout <<"\nTotal kombinasi yang ada pada source data adalah " <<penghitung <<"\n";
cout <<"\nDetected karakter adalah " <<inputChecker;
cout <<"\nThe Decimal is :" <<inputChecker;
}
I want to make that last one which is "Decimal" to show converted inputChecker from binary to decimal. Is there any function to easily convert from binary to decimal in c++?
Thanks in advance :))

Use std::strtol with 2 as the base. For example,
auto result = std::strtol(source.c_str(), nullptr, 2);

For brute force:
static const std::string text_value("10010101001011110101010001");
const unsigned int length = text_value.length();
unsigned long numeric_value = 0;
for (unsigned int i = 0; i < length; ++i)
{
value <<= 1;
value |= text_value[i] - '0';
}
The value is shifted or multiplied by 2, then the digit is added to the accumulated sum.
Similar in principle to converting decimal text digits to internal representation.

Related

I wrote code to convert decimal fraction number to its binary equivalent. It compiles fine but when executed hangs

I wrote code to convert decimal fraction number to its binary equivalent. It compiles fine but when executed hangs. The code here prints only first four digits of the binary conversion and if the number if with more than 4 digits, it shows '...' after it. On execution it hangs. Help!
#include <iostream>
using namespace std;
int main()
{
int i, x[10];
float num;
cout << "**PROGRAM TO CONVERT DECIMAL FRACTION INTO ITS EQUIVALENT BINARY**\n";
cout << "Enter a fraction in between 0 to 1 for conversion: ";
cin >> num;
if (num>=0 && num<=1)
{
i=1;
while (num!=1.000)
{
num*=2;
x[i]=num;
num=num-x[i];
i++;
}
if (i>4)
{
cout << "The binary equivalent is 0.";
for (i=1;i<=4;i++)
{
cout << x[i];
}
cout << "...";
}
else
{
cout << "The binary equivalent is 0.";
for (i=1;i<=4;i++)
{
cout << x[i];
}
}
}
else
{
cout << "The number entered is out of range.";
}
return 0;
}
The first obstacle is the infinite while loop:
Assuming input num=0.5
after first iteration, i=1, x[0]=1, num=0.0
after second iteration, i=2, x[1]=0, num=0.0
Continue forever, i=..., x[i-]1=0, num=0.0
With nothing to break the loop.
while (num!=1.000)
{
num*=2;
x[i]=num;
num=num-x[i];
i++;
}
To fix, consider few changes. There might be other issues.
put a limit on the while loop (i<10 should be a good condition, as this is the size of the x array), or i=4, as this is the maximum output.
The break condition for the while loop should probably be 'num != 0', or even better (num > 1e-7, or other small value).
float has 23 bit in mantissa, maybe it is because you are assign x[i] with i greater than 9.
try this:
//stop when you get four bits
while (i< 5)
Original code has several issues:
1 For input num=.5 and similar (really for all values) cycle never ends (dash-o suggested fix ideas)
2 array x[10] is overflowed with undefined behavior (Edney)
3 nitpicking: 1 is not a “fraction” and better check for a range 0 <= num < 1 instead of 0 <= num <= 1(see also OP printing code; 1 could be added); we could use x[4] with 0<=i <=3
4 string could also be used (PaulMcKenzie). Really “>>” uses string processing for parsing and calculating binary equivalent from which by multiplying by 2 (left shit) and truncation fractional part the code calculates target bits. Both approaches give correct identical results; implementing by string we need to add internal to operator “>>” implementation code to parsing valid formats for floats (decimals) such as 3.14e-1, .2718, 1e-1, etc.
This fix follows OP:
#include <iostream>
using namespace std;
int main()
{
int i, x[5];
float num;
cout << "**PROGRAM TO CONVERT DECIMAL FRACTION INTO ITS EQUIVALENT BINARY**\n";
cout << "Enter a fraction in between 0 to 1 for conversion: ";
cin >> num;
if (num>=0 && num<1)
{
i=1;
while (i<=4)
{
num*=2;
x[i]=num;
num=num-x[i];
i++;
}
cout << "The binary equivalent is 0.";
for (i=1;i<=4;i++)
{
cout << x[i];
}
if (num>0)
cout << "...";
}
else
{
cout << "The number entered is out of range.";
}
return 0;
}
This code is without cycles (they are in code implementing “>>”, bitset):
#include <iostream>
#include <bitset>
using namespace std;
int main () {
const int digits = 4;
int fraction;
float num;
cout << "**PROGRAM TO CONVERT DECIMAL FRACTION INTO ITS EQUIVALENT BINARY**\n";
cout << "Enter a fraction in between 0 to 1 for conversion: ";
cin >> num;
if (num >= 0 && num < 1) {
fraction = num = num * pow (2, digits);
cout << "The binary equivalent is 0.";
cout << bitset<digits> (fraction);
if (num - fraction > 0) cout << "...";
}
else cout << "The number entered is out of range.";
}

C++ convert binary to decimal, octal

Please i need help debugging the code below.
I am suppose to produce a code using functions that converts binary numbers to decimal or octal.
I keep getting error at the switch statement "error too few argument in function call".
#include <iostream.>
long int menu();
long int toDeci(long int);
long int toOct(long int);
using namespace std;
int main ()
{
int convert=menu();
switch (convert)
{
case(0):
toDeci();
break;
case(1):
toOct();
break;
}
return 0;
}
long int menu()
{
int convert;
cout<<"Enter your choice of conversion: "<<endl;
cout<<"0-Binary to Decimal"<<endl;
cout<<"1-Binary to Octal"<<endl;
cin>>convert;
return convert;
}
long int toDeci(long int)
{
long bin, dec=0, rem, num, base =1;
cout<<"Enter the binary number (0s and 1s): ";
cin>> num;
bin = num;
while (num > 0)
{
rem = num % 10;
dec = dec + rem * base;
base = base * 2;
num = num / 10;
}
cout<<"The decimal equivalent of "<< bin<<" = "<<dec<<endl;
return dec;
}
long int toOct(long int)
{
long int binnum, rem, quot;
int octnum[100], i=1, j;
cout<<"Enter the binary number: ";
cin>>binnum;
while(quot!=0)
{
octnum[i++]=quot%8;
quot=quot/8;
}
cout<<"Equivalent octal value of "<<binnum<<" :"<<endl;
for(j=i-1; j>0; j--)
{
cout<<octnum[j];
}
}
I am suppose to produce a code using functions that converts binary numbers to decimal or octal.
There's no such thing like converting binary numbers to decimal or octal based on numerical representations as
long int toDeci(long int);
long int toOct(long int);
Such functions are completely nonsensical for any semantical interpretation.
Numbers are numbers, and their textual representation can be in decimal, hex, octal or binary format:
dec 42
hex 0x2A
oct 052
bin 101010
are all still the same number in a long int data type.
Using the c++ standard I/O manipulators enable you to make conversions of these formats from their textual representations.
I'm not sure that I understand what you're trying to do. Here's an example that might help you (demo):
#include <iostream>
int main()
{
using namespace std;
// 64 bits, at most, plus null terminator
const int max_size = 64 + 1;
char b[max_size];
//
cin.getline( b, max_size );
// radix 2 string to int64_t
uint64_t i = 0;
for ( const char* p = b; *p && *p == '0' || *p == '1'; ++p )
{
i <<= 1;
i += *p - '0';
}
// display
cout << "decimal: " << i << endl;
cout << hex << "hexa: " << i << endl;
cout << oct << "octa: " << i << endl;
return 0;
}

Program in c++ tell if a number is integer or float

I used function overload to check if an input number is integer or float. However I get this following error:
error: call of overloaded 'retNr(double)' is ambiguous|
#include <iostream>
using namespace std;
void retNr(int x)
{
cout << "The entered number is an integer. " << endl;
}
void retNr(float x)
{
cout << "The entered number is a float. " << endl;
}
int main()
{
cout << "Please enter a number: " << endl;
cin >> nr;
retNr(nr);
return 0;
}
Read from cin into a string and then check the string for the presence of a decimal point. If there is a decimal point, call atof() on the string to convert it to a float, otherwise call atoi() to convert it to an integer.
Make some small change in:
void retNr(double x)
{
cout << "The entered number is a double. " << endl;
}
Remember to declare your nr variable.
double d = 1.0;
int i = 1;
retNr(d);
retNr(i);
You will have to initialize nr first.
Then you can use integer read & check it with a float if there is dot, ie ch=='.'
Thus, your program will be like this:
#include <iostream>
using namespace std;
int main()
{
int nr = 0; char ch;
cout << "Please enter a number: " << endl;
cin >> nr;
cin.get(ch);
if(ch=='.')
{
cout << "The entered number is a float. " << endl;
}
else
{
cout << "The entered number is an integer. " << endl;
}
return 0;
}
It's not too clear what you're asking for. If you really want
to know whether a number is an integer or not, then use modf
on it:
bool
isInt( double d )
{
double dummy;
return modf( d, &dummy ) == 0.0;
}
If you're reading a number, then read it as a double, and then
use the above.
If you want to trigger off the format of the input (i.e.
"10.0" will be treated as a floating point, even though it is
an integer), then read the input as a string, then try to
convert it to int; if this eats all of the input, then it was
entered as an int (no decimal or exponent), otherwise, try the
same thing treating it as a double:
std::string entry;
std::cin >> entry;
char const* end;
long i = strtol( entry.c_str(), &end, 10 );
if ( *end == '\0' ) {
// entry was entered in integral format...
} else {
double d = strtod( entry.c_str(), &end );
if ( *end == '\0' ) {
// entry was entered in floating point format...
} else {
// entry wasn't a number...
}
}
I'd advise against this, however; it will only confuse your
users if 0 isn't 0.0.
You may use abs() function for this issue.
#include<stdio.h>
#include<math.h>
int main()
{
double input;
scanf("%lf",&input);
int absulate = abs(input);
printf( (input==absulate)? "It is integer\n" : "It is float");
return 0;
}
float num = 7;
int n = (int)num;
float n1 = (float)n;
if(num == n1)
{
cout << "Integer\n";
}
else
{
cout << "Not Integer\n";
}
The question is wrong in its essence: A number it is not a float or an integer, but could be represented as a float or as an integer ( of course certain representation has some limitations )
So if I wrote '10' why should I say this is an integer? Could be a float too! Just if I want to use it as a float I would represent it as a float.

Fibonacci series in C++ can't get more than 47 numbers

I designed this program that can print the Fibonacci Series (series[i] = series[i-1] + series[i-2]) but i can't get more than 47 numbers because the 48th they become negative and strange numbers (i think this happens when the list is out of range or the item is null):
#include <iostream>
#include <vector>
using namespace std;
int main ()
{
int length;
string again = "";
do {
cout << "Enter the length you want in your sequence: ";
cin >> length;
vector<int> series(length);
for (int n=0; n<=1; n++) series[n] = n;
for (int number=2; number<=length; number++) {
series[number] = series[number-1] + series[number-2];
}
for (int i=0; i<length; i++) cout << series[i] << " ";
cout << endl << "Do it again ? <y/n> ";
cin >> again;
cout << endl;
} while (again == "y");
}
EDIT:
"Improved" code:
#include <iostream>
#include <vector>
#include <string>
std::vector<int> fibonacci (int length)
{
std::vector<int> series(length);
series[0] = 0;
series[1] = 1;
for (int num=2; num<length; num++) {
series[num] = series[num-1] + series[num-2];
}
return series;
}
int main ()
{
std::string again;
do {
std::cout << "Enter how many numbers you want in your series: ";
int length;
std::cin >> length;
std::vector<int> series(length);
series = fibonacci(length);
for (int n=0; n<length; n++) std::cout << series[n] << " ";
std::cout << "\nDo it again <y/n> ? ";
std::cin >> again;
std::cout << std::endl;
} while (again == "y");
}
When you get to the 47th value, the numbers go out of int range. The maximum int value is 2,147,483,647 and the 46th number is just below at 1,836,311,903. The 47th number exceeds the maximum with 2,971,215,073.
Also, as LeonardBlunderbuss mentioned, you are exceeding the range of the vector with the for loop that you have. Vectors start with 0, and so by having number<=length; the range+1 element will be called. The range only goes up to length-1.
You are encountering integer overflow, meaning that you are trying to calculate a number that is outsize of the bounds of INT_MAX and INT_MIN. In the case of an unsigned number, it just overflows to zero and starts over, while in the case of a signed integer, it rolls over to INT_MIN. In both cases this is referred to as integer overflow or integer wraparound.
You could put a band-aid on the solution by using long long int (likely 64-bits on most modern systems) instead of int for your primitive data type, or you could use a better approach like a library that supports (almost) arbitrarily long data types, like libBigInteger.
References
Integer Overflow, Accessed 2014-03-04, <http://en.wikipedia.org/wiki/Integer_overflow>
C++ Big Integer Library, Accessed 2014-03-04, <https://mattmccutchen.net/bigint/>
The limits.h Header File, Accessed 2014-03-04, <http://tigcc.ticalc.org/doc/limits.html>
This is my solution to calculating BIG fibonacci numbers
// Study for algorithm that counts n:th fibonacci number
#include <iostream>
#include <cstdlib>
#include "boost/multiprecision/cpp_int.hpp"
#define get_buffer(a) buffer[(a)%2]
#define BIG boost::multiprecision::cpp_int
int main(int argc, const char* argv[])
{
// atoi returns 0 if not integer
if(argc != 2 || atoi(argv[1]) < 1){
std::cout << "You must provide one argument. Integer > 0" << std::endl;
return EXIT_SUCCESS;
}
// ring buffer to store previous two fibonacci number, index it with [i%2]
// use defined function get_buffer(i), it will do the magic for you
BIG buffer[2]={ 1, 1 };
// n:th Fibonacci
unsigned int fn = atoi(argv[1]);
// count loop is used if seeked fibonacci number is gt 2
if(fn > 2){
for(unsigned int i = 2; i < fn; ++i){
get_buffer(i) = get_buffer(i-1) + get_buffer(i-2);
// get_buffer(i-1) + get_buffer(i-2) == buffer[0] + buffer[1]
// if you want to print out every result, do it here
}
}
// Result will be send to cout
std::cout << "Fibonacci[" << fn << "] is " << get_buffer(fn-1) << std::endl;
return EXIT_SUCCESS;
}

C++ Loops - inputting integers until user quits

well I'm trying to get the user to input an integers as much as they want, until they input a negative number. 1st step was to use the ATOF function to convert string to number(which I did), and then allow the user to input integers(I only manage to do once just to see if I can use the atof function correctly.
Any help/tips is appreciated on giving me the right direction.
Here is my code thus far:
#include <iostream>
#include <string>
int main() {
using namespace std;
char buffer[256];
char tempBuff[256] = {'\n'};
double result;
int count = 0;
cout << "Testing " << endl;
cout << "Enter Any integers: ";
cin.getline(buffer,256);
for(int i = 0; i < strlen(buffer); i++)
{
if(isdigit(buffer[i]))
{
tempBuff[count] = buffer[i];
count++;
}
}
if (atof(tempBuff) > 0) {
result = atof(tempBuff) / 2;
}
cout << endl << "The integer you put was: " << tempBuff
<< " And dividing the integers "<< result << endl;
cin.ignore();
return 0;
}
How is atof supposed to know how many valid digits tempBuff contains? The atof function only accepts a C-style string as its input. Otherwise, it has no way to know how many characters are valid.
You can use tempBuff[count] = 0; before the call of atof. A C-style string is terminated by a zero byte.