Conversion of Binary to Decimals - c++

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.

Related

Trouble in looping while printing a series

I have to write a program in C++ that will print a sequence of 10 numbers based on user supplied variable input.
Expected output:
Input a number: 10
Series: 11 13 16 20 25 31 38 46 55 65
Here is my code so far:
#include <stdio.h>
int main()
{
int j, sum = 0, b=1;
for (j = 10; j <= 65; j=j+b++)
{
sum = sum + j;
printf("%d\n",j);
}
}
I've hardcoded it with respect to the given sample. How can I make it work for variable inputs?
Here is a solution that is almost complete, your part of job is to update one line where comment says /* ??? */
See code comments for more info:
#include <iostream>
int main()
{
// Starting value, ex. 10, chosen by user
int input = 0;
// Length of the sequence, also chosen by user
int length = 0;
// Sequence is incremented according to the pattern you already know
// for more info see:
// https://www.mathsisfun.com/algebra/sequences-sums-arithmetic.html
int adder = 0;
// Ask user to input starting number
std::cout << "Please enter the starting number: ";
std::cin >> input;
// TODO: verify user input is number
// Ask user for desired length of a sequence
std::cout << "Please enter the desired length of sequence: ";
std::cin >> length;
std::cout << "Generating sequence..." << std::endl;
// Generate sequence
// TODO: your part of job is to replace the ???
for (int counter = 0; counter < length; ++counter, input += /* ??? */)
{
// Show the current number in the sequence
std::cout << input << std::endl;
}
return 0;
}
I think this is the solution:
#include <iostream>
using namespace std;
int main() {
int n;
cin >>n;
int lastNumber=n;
for (int i=1; i<=n; i++) {
lastNumber+=i;
cout <<lastNumber <<' ';
}
endl(cout);
}

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

How to get length of int variable as string have builtin function e.g string.length()

Is there any way to get the length of int variable e.g In string we get the length by simply writing int size = string.length();
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int i = 0;
cout<<"Please Enter the value of i"<<endl;
cin>>i;
//if user enter 123
//then size be 3 .
// Is it possible to find that size
}
#include <cassert>
#include <cmath>
#include <iostream>
using namespace std;
int main () {
assert(int(log10(9)) + 1 == 1);
assert(int(log10(99)) + 1 == 2);
assert(int(log10(123)) + 1 == 3);
assert(int(log10(999)) + 1 == 3);
return 0;}
You have a few options here:
(This answer assumes you mean number of printable characters in the integer input)
Read the input as a string and get its length before converting to an int. Note that this code avoids error handling for brevity.
#include <iostream>
#include <sstream>
using namespace std;
int main(int argc, char** argv) {
cout << "Please enter the value of i" << endl;
string stringIn = "";
cin >> stringIn;
cout << "stringIn = " << stringIn << endl;
size_t length = stringIn.length();
cout << "input length = " << length << endl;
int intIn;
istringstream(stringIn) >> intIn;
cout << "integer = " << intIn << endl;
}
Read in an integer and count the digits directly:
Many other answer do this using log. I'll give one that will properly count the minus sign as a character.
int length_of_int(int number) {
int length = 0;
if (number < 0) {
number = (-1) * number;
++length;
}
while (number) {
number /= 10;
length++;
}
return length;
}
Derived from granmirupa's answer.
Not sure whether it fits your requirement but you could use std::to_string to convert your numeric data to string and then return its length.
For length i assume you mean the number of digits in a number:
#include <math.h>
.....
int num_of_digits(int number)
{
int digits;
if(number < 0)
number = (-1)*number;
digits = ((int)log10 (number)) + 1;
return digits;
}
Or:
int num_of_digits(int number)
{
int digits = 0;
if (number < 0) number = (-1) * number;
while (number) {
number /= 10;
digits++;
}
return digits;
}
Onother option could be this (can works with float too, but the result is not guaranteed):
#include <iostream>
#include <sstream>
#include <iomanip>
...........
int num_of_digits3(float number){
stringstream ss;
ss << setprecision (20) << number;
return ss.str().length();
}

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