C++ convert binary to decimal, octal - c++

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

Related

Conversion of Binary to Decimals

I am writing a c++ program where the program takes the t test cases as input and asks the binary input t times, and after that displays the output.
I tried to code but for 1st test case it displays right output in decimal format but for further test cases its not displaying correct output result.
#include<iostream>
#include<cmath>
using namespace std;
int main() {
long int num;
int r=0,i=0,t,dec=0;
cin>>t;
while(t--) {
cin>>num;
while (num!=0) {
r = num% 10;
num /= 10;
dec += r * pow(2, i);
++i;
}
cout<<dec<<"\n";
}
return 0;
}
This code if run for lets say 2 test cases , lets say first one is 101 , it displays 5 which is fine but on the second input , lets say 111 , it displays output 61.
I am not sure where I am getting it wrong.
You initialize i, dec outside the outer while loop. Initialize them to 0 inside the outer while loop and it works:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int t;
cin >> t;
while(t--)
{
int num, r, dec = 0, i = 0;
cin >> num;
while (num != 0) {
r = num % 10;
num /= 10;
dec += r * pow(2, i);
//cout << r << " " << num << " " << i << " " << dec << endl;
++i;
}
cout << dec << "\n";
}
return 0;
}
There is C function strtoull, which is doing the job
Example:
cat bin2dec.cpp
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main() {
string num;
int t;
cin>>t;
while(t--) {
cin>>num;
auto dec = strtoull(num.c_str(), NULL, 2);
cout << dec << endl;
}
return 0;
}
g++ -O2 -o bin2dec bin2dec.cpp
2
111
7
100000000000
2048
g++ --version | head -1
g++ (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
While you can use the division and remainder method, C++ provides std::bitset and the string conversion std::stoul, std::stoull that can automate the conversion for you.
The following example loops prompting the user for input of a binary value and converts the value to unsigned long so long as the binary digits entered are 64 or less. Simply press Enter without entering a value to end the program:
#include <iostream>
#include <string>
#include <bitset>
int main() {
for (;;) { /* loop continually */
std::string input{}; /* binary input from user */
unsigned long value = 0; /* value to hold conversion to ulong */
/* prompt for input, read/validate input */
std::cout << "\nenter a binary value: ";
if (!getline(std::cin, input) || input.size() == 0) {
break;
}
if (input.size() > 64) { /* validate 64 binary digits or less */
std::cerr << "error: input exceeds 64-bit conversion limit.\n";
continue;
}
value = std::bitset<64>(input).to_ulong(); /* convert to ulong */
std::cout << input << ": " << value << '\n'; /* output result */
}
}
Note: you would also want to validate the user has entered only '0's and '1's which you can do simply with std::basic_string::find_first_not_of, e.g.
if (input.find_first_not_of("01") != std::string::npos) {
std::cerr << "error: invalid input not '0' and '1'\n";
continue;
}
(simply add the if statement before the conversion and assignment to value)
Example Use/Output
./bin/bitset_to_ulong
enter a binary value: 1010
1010: 10
enter a binary value: 10000000
10000000: 128
enter a binary value: 1111
1111: 15
enter a binary value: 1234
error: invalid input not '0' and '1'
enter a binary value:
Just an alternative way of doing the same that C++ has provided a convenient way to do in C++11 and forward.

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++ Converting octal fraction to decimal fraction?

I'm currently working on a program that is meant to take an octal fraction as an input and convert it to a decimal fraction. So far, I have the part of code that will convert the portion before the decimal point to decimal, just not the floating points after the decimal point. I was trying to use modulus, but was unsuccessful because of my variable being a float.
Is there a way to convert the remaining numbers after the decimal point to decimal from octal? I have posted my code below. Any help is appreciated. Thanks!
int main()
{
float num;
int rem = 0;;
int dec = 0;
int i = 0;
cout << "Please enter a number with a decimal point: ";
cin >> num;
double ohalf = num - (int)num;
int half = num;
while (half != 0)
{
rem = half % 10;
half /= 10; //Converts first have to decimal
dec += rem *= pow(8, i);
i++;
}
cout << dec;
i = -1;
while (ohalf != 0)
{
rem = ohalf *pow(8, i); //Converts second half to decimal. *This is where I am stuck*
i--;
}
cout << rem;
_getch();
return 0;
}
Going with the idea that one can remove the decimal point just by multiplying with the base often enough:
"123.456" in base 16
=> BASE16("1234.56")/16
=> BASE16("12345.6")/(16*16)
=> BASE16("123456")/(16*16*16)
or
"123.456" in base 8
=> BASE8("1234.56")/8
=> BASE8("12345.6")/(8*8)
=> BASE8("123456")/(8*8*8)
So all we need to know is the number of places behind the decimal point.
Then we can remove it and use std::stoi to convert the remaining string in the wanted base.
As a last step we need divide again through base^number_of_places_after_decimal.
Putting everything together you get something like this:
#include <iostream>
#include <string>
#include <cmath>
using std::cout;
using std::cin;
using std::string;
int main()
{
int base = 8;
string value;
cout << "Please enter a number with a decimal point: ";
cin >> value;
size_t ppos = value.find('.');
if (ppos != string::npos) {
value.replace(ppos,1,"");
} else {
ppos = value.size();
}
size_t mpos = 0;
double dValue = (double)std::stoi(value, &mpos, base);
if (mpos >= ppos)
{
dValue /= std::pow(base, (mpos - ppos));
}
std::cout << dValue << '\n';
return 0;
}
If you're confident that both the integer and fractional parts of your floating-point value won't overflow the range of long long int, you could parse both parts separately with std::stoll(), then divide the fractional part by the appropriate power of 8:
#include <cmath>
#include <stdexcept>
#include <string>
double parse_octal_fraction(const std::string s)
{
std::size_t dotpos;
auto whole = std::stoll(s, &dotpos, 8);
if (dotpos+1 >= s.length())
// no fractional part
return whole;
std::size_t fract_digits;
auto frac = std::stoll(s.substr(dotpos+1), &fract_digits, 8);
if (s.find_first_not_of("01234567", dotpos+1) != std::string::npos)
throw std::invalid_argument("parse_octal_fraction");
return whole + frac / std::pow(8, fract_digits);
}
#include <iostream>
int main()
{
for (auto input: { "10", "0", "1.", "0.4", "0.04", "1.04", "1.04 ", "1. 04"})
try {
std::cout << input << " (octal) == " << parse_octal_fraction(input) << " (decimal)" << std::endl;
} catch (const std::invalid_argument e) {
std::cerr << "invalid input: " << e.what() << " " << input << std::endl;
}
}
The test inputs shown give this output:
10 (octal) == 8 (decimal)
0 (octal) == 0 (decimal)
1. (octal) == 1 (decimal)
0.4 (octal) == 0.5 (decimal)
0.04 (octal) == 0.0625 (decimal)
1.04 (octal) == 1.0625 (decimal)
invalid input: parse_octal_fraction 1.04
invalid input: parse_octal_fraction 1. 04
in your code
while (ohalf != 0)
{
rem = ohalf *pow(8, i); //Converts second half to decimal. *This is where I am stuck*
i--;
}
ohalf will never be equal to zero so It may have lead to infinite loop

C++ convert binary to decimal from string input

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.

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.