Checking for binary input and conversion

In my function to check if the input value was binary or not, I am struggling with the how i should do that exactly. What should I put as my else if condition?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
  
#include "stdafx.h"
#include<iostream>
#include<limits>

using namespace std;
using namespace System;

void ConvertByRecursion(long long n);
long long getDecimal();
long long GetBin();
void bin_dec(long long n);

int main()
{
	long long n;
	int ans;

	cout << "Welcome to my decimal to binary converter" << endl;
	cout << "Please hit 1 for decimal to binary, 2 for binary to decimal, and 0 to quit" << endl;
	cin >>ans; 

	if (ans == 1)
	{
		n = getDecimal();
		while (n != 0)
		{
			ConvertByRecursion(n);
			cout << endl << endl;
			n = getDecimal();
		}
	}
	else if (ans == 2)
	{ 
		n = GetBin();
		while (n !=0)
		{
			bin_dec(n);
			n = GetBin();
		}
	}
	else 

	cout << "Thanks for using my converting program" << endl;
	system("Pause");
    return 0;
}

long long getDecimal()
{

	long long n;
	bool baddata = false;

	do
	{
		baddata = false;
		cout << "Please enter your decimal value to convert: ";
		cin >> n;
		if (!cin.good())
		{
			cin.clear();
			cin.ignore(numeric_limits<streamsize>::max(), '\n');
			cout << "I could not decifer your input as a decimal value" << endl;
			baddata = true;
		}
		else if (n < 0)
		{
			cout << "Please enter a non-negative number" << endl;
			baddata = true;
		}
	
	} while (baddata);
	
		return n;
	
}

void ConvertByRecursion(long long n)
{
	long long r;
	long long newval;
	r = n % 2;
	newval = n / 2;
	Console::WriteLine("Decimal {0,12:D} divided by 2 ={1,12:D} w/ remainded of {2,3:D} ", n, newval, r);
	if (newval>0)
	{
		ConvertByRecursion(newval);
	}
	else
	{
		cout << "The binary value is: ";
	}
	cout << r;
}
long long GetBin()
{
	long long n;
	bool baddata = false;
	
	do
	{
		baddata = false;
		cout << "Please input the binary number to be converted to decimal: ";
		cin >> n;
		if (n < 0)
		{
			cout << "Please input a non-negative number" << endl;
			baddata = true;
		}
		else if (n%10 != 0 || n%10 != 1)
		{
			cout << "Please input a correct binary number" << endl;
			baddata = true;
		}

		else if (!cin.good())
		{
			cin.clear();
			cin.ignore(numeric_limits<streamsize>::max(), '\n');
			cout << "I could not decifer your input as a binary value" << endl;
			baddata = true;
		}
	} while (baddata);
	
		return n;
}
void bin_dec(long long n)
{
	double num = 0;
	double rem;
	int i = 0;
	
	

	
	while (n != 0)
	{
		rem = n % 10;
		n /= 10;
		num += (rem)*pow(2, i);
		++i;
	}
	cout << "The decimal value is: " << num << endl;
}
or would it be easier to implement the check in the actual conversion function? I am 'supposed' to implement the check in a seperate function, but I am not sure on how to do it unless I actually calculate it
For GetBin(), I think you have to resort to using char and/or string:


1. Offline algorithm: You can have the user input digits into a string variable. Then loop through the string and test to see if any of the char are not '1' or '0'.


2. Online algorithm: You can modify the do-while loop so that you cin >> ch, where ch is a char type instead of a long long. For each user cin, you check to see if it is '1' or '0'. And if it is '1' or '0', add it to a string. The user will keep on inputting '1' or '0' until they enter an invalid data. You can test if the data is invalid and exit the loop if it is, or do whatever else you want.


else if (n%10 != 0 || n%10 != 1)
The conditional above won't catch all non-binary numbers, e.g., 150 % 10 = 0. So even though 150 is not binary the condition above won't catch this fact.
Last edited on
Yea, i realized my else if function right now doesn't work for most numbers, thank you. Could I convert my long long n in my else if function to a string inside the loop, and check each char there?

getBin() function, sorry
Last edited on
You only need one loop for offline algorithm.

This is the pseudocode of offline algorithm:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
string GetBin()
{
    string user_input;
    bool baddata = false;
    
    //ask the user here.


    //no need to loop cin for offline algorithm
    //user enters all data at once
    cin >> user_input;

    for(int i = 0; i < user_input.size(); i++)
    {
        if(user_input[i] != "0" || user_input[i] != "1" )
            baddata = true

        //check to see if baddata is true
        //if it is, reset counter i
        //alternatively use a while loop
    }

    return user_input; //return binary data as string
}


Note: You probably want to keep binary number as string in case you need to evaluate each bit in the future.
Last edited on
I decided to create a new function for this. It is saying I need pointer to for my 'i' and my .size isn't working, do I need a new header? Also, where would I put the function call in my program, right before or after when i call GetBin()?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 void isbin(long long n)
{
	bool baddata = false;
	int i = 0;

std::ostringstream ss;
ss << n;

std::string result = ss.str();

for (i = 0; i<n.size(); i++)
{
	if (n[i] != '1' && n[i] != '0')
	{
		cout << "Please input a true binary number" << endl;

	}
}

}
n needs to be string not long long.

Use this header:

#include <string>

Create a binary parser function to convert string of bits to decimal:

1
2
3
4
5
6
7
8
9
10
11
12

long long stringBitstoDecimal(string n)
{
     long long decimal;

     //go through each place in string using loop
     //you can do this because string is an array of characters, so you can use [] operator to access each element.
     //accumulate decimal value in decimal

    return decimal;
}


If you need to learn what string is and how to use it go here:

http://www.cplusplus.com/reference/string/string/
Last edited on
I would put it in the same function as GetBin(), but I wouldnt know how to check if it was negative? Would I still have to convert it to check or is there a way to check if a string is '0' ?
You can have negative binary using 2's complement.

If you don't want negative binaries then you can just assume the binaries entered by user is unsigned.

The answer is that it depends on how you interpret the binary string.
Last edited on
I am "almost" there, I think. I am now getting an infinite loop sometimes or it will try to convert a non binary into decimal.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
// BinDecConversion.cpp : main project file.

#include "stdafx.h"
#include<iostream>
#include<limits>
#include<string>
#include<sstream>
#include<math.h>

using namespace std;
using namespace System;

void ConvertByRecursion(long long n);
long long getDecimal();
long long GetBin();
void bin_dec(long long n);
void isbin(string k);

int main()
{
	long long n;
	int ans;
	string k;

	cout << "Welcome to my decimal to binary converter" << endl;
	cout << "Please hit 1 for decimal to binary, 2 for binary to decimal, and 0 to quit" << endl;
	cin >>ans; 

	if (ans == 1)
	{
		n = getDecimal();
		while (n != 0)
		{
			ConvertByRecursion(n);
			cout << endl << endl;
			n = getDecimal();
		}
	}
	else if (ans == 2)
	{ 
		
		n = GetBin();
		isbin(k);
		while (n !=0)
		{
			bin_dec(n);
			n = GetBin();
		}
	}
	else 

	cout << "Thanks for using my converting program" << endl;
	system("Pause");
    return 0;
}

long long getDecimal()
{

	long long n;
	bool baddata = false;

	do
	{
		baddata = false;
		cout << "Please enter your decimal value to convert: ";
		cin >> n;
		if (!cin.good())
		{
			cin.clear();
			cin.ignore(numeric_limits<streamsize>::max(), '\n');
			cout << "I could not decifer your input as a decimal value" << endl;
			baddata = true;
		}
		else if (n < 0)
		{
			cout << "Please enter a non-negative number" << endl;
			baddata = true;
		}
	
	} while (baddata);
	
		return n;
	
}

void ConvertByRecursion(long long n)
{
	long long r;
	long long newval;
	r = n % 2;
	newval = n / 2;
	Console::WriteLine("Decimal {0,12:D} divided by 2 ={1,12:D} w/ remainded of {2,3:D} ", n, newval, r);
	if (newval>0)
	{
		ConvertByRecursion(newval);
	}
	else
	{
		cout << "The binary value is: ";
	}
	cout << r;
}
long long GetBin()
{
	long long n;
	bool baddata = false;
	
	do
	{
		baddata = false;
		cout << "Please input the binary number to be converted to decimal: ";
		cin >> n;
		if (n < 0)
		{
			cout << "Please input a non-negative number" << endl;
			baddata = true;
		}
		

		else if (!cin.good())
		{
			cin.clear();
			cin.ignore(numeric_limits<streamsize>::max(), '\n');
			cout << "I could not decifer your input as a binary value" << endl;
			baddata = true;
		}
	} while (baddata);
	
		return n;
}
void bin_dec(long long n)
{
	double num = 0;
	double rem;
	int i = 0;
	
	

	
	while (n != 0)
	{
		
		rem = n % 10;
		n /= 10;
		num += (rem)*pow(2, i);
		++i;
	}
	cout << "The decimal value is: " << num << endl;
}

 
void isbin(string k)
{
	bool baddata = false;
	int i = 0;


std::ostringstream ss;
ss << k;

std::string result = ss.str();

for (i = 0; i<k.size(); i++)
{
	if (k[i] != '1' && k[i] != '0')
	{
		cout << "Please input a true binary number" << endl;

	}
}

}
We aren't 'supposed' to have negative, so I assume we aren't using 2's compliment.
isbin() should return a bool type. I am giving you semi-pseudo codes, so they aren't supposed to run or compile as it is.

You don't need ostringstream. You also don't need baddata since isbin() function itself will be telling whether the binary is bad or good.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

//in main:
int main()
{
    //...
    string input;
    cout << "Please input a binary number" << endl;
    cin >> input;

    while( !isbin(input) )
    {
        cout << "Please input a true binary number" << endl;
        cin >> input;
    }

    //...

}

//...some codes later

bool isbin(string k)
{
    int i = 0;

    for (i = 0; i<k.size(); i++)
    {
         if (k[i] != '1' && k[i] != '0')
		return false;
	
    }

    return true;
}
Last edited on
Ok, thank you a lot. I will try implementing that now. Also, I tried thinking of it a different way similar to my first way (which was wrong). Why doesn't this work now?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void test_bin(long long n)
{

	
		long long ans;
		while (n != 0 && n != 1)
		{
			ans = n % 10;
			if (ans > 1)
			{
				n %= 10;

			}
			else
				cout << "That is not a binary number" << endl;
		}
		
	
}
That works, but you're trading run time for memory. And you lose the ability to edit the bits efficiently. Each time you want to recalculate the bits, you need to perform modulus operations. Whereas in a string, you're simply accessing the bits. Notice that you need to go through each bit to convert to decimal.

But it all comes down to what you want for your program. If you don't need to edit bits or do a lot of bit calculations, then use the test_bin() you have created.

The reason why string is better is because you can implement more simple bitwise operations. E.g., 001010 AND 100000 = 101010. With string implementation, you just compare each bit. In modulus implementation, you have to do modulus to both simultaneously before you can compare. But string uses more memory. This is a trade off you have to decide on.

However, in this day and age, memory is usually more expendable than time.

EDIT: I forgot to say this, if you're not using negative integers, use unsigned long long.
Last edited on
I don't think that that matters much for this project, but I will think about that in my future endeavors. However, when i type in a non-binary number (ex. 555), my program does not give me an error message. It goes through with the calculation (I think). Also, sorry to always post my whole program, I am not sure which parts are pertinent to my question usually.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
#include "stdafx.h"
#include<iostream>
#include<limits>

using namespace std;
using namespace System;

void ConvertByRecursion(long long n);
long long getDecimal();
long long GetBin();
void bin_dec(long long n);
void test_bin(long long n);



int main()
{
	long long n;
	int ans;
	string k;

	cout << "Welcome to my decimal to binary converter" << endl;
	cout << "Please hit 1 for decimal to binary, 2 for binary to decimal, and 0 to quit" << endl;
	cin >>ans; 

	if (ans == 1)
	{
		n = 
		n = getDecimal();
		
		while (n != 0)
		{
			ConvertByRecursion(n);
			cout << endl << endl;
			n = getDecimal();
		}
	}
	else if (ans == 2)
	{ 
		test_bin(n);
		n = GetBin();
		
		
		while (n !=0)
		{
			bin_dec(n);
			n = GetBin();
		}
	}
	else 

	cout << "Thanks for using my converting program" << endl;
	system("Pause");
    return 0;
}

long long getDecimal()
{

	long long n;
	bool baddata = false;

	do
	{
		baddata = false;
		cout << "Please enter your decimal value to convert: ";
		cin >> n;
		if (!cin.good())
		{
			cin.clear();
			cin.ignore(numeric_limits<streamsize>::max(), '\n');
			cout << "I could not decifer your input as a decimal value" << endl;
			baddata = true;
		}
		else if (n < 0)
		{
			cout << "Please enter a non-negative number" << endl;
			baddata = true;
		}
	
	} while (baddata);
	
		return n;
	
}

void ConvertByRecursion(long long n)
{
	long long r;
	long long newval;
	r = n % 2;
	newval = n / 2;
	Console::WriteLine("Decimal {0,12:D} divided by 2 ={1,12:D} w/ remainded of {2,3:D} ", n, newval, r);
	if (newval>0)
	{
		ConvertByRecursion(newval);
	}
	else
	{
		cout << "The binary value is: ";
	}
	cout << r;
}
long long GetBin()
{
	long long n;
	bool baddata = false;
	
	do
	{
		baddata = false;
		cout << "Please input the binary number to be converted to decimal: ";
		cin >> n;
		if (n < 0)
		{
			cout << "Please input a non-negative number" << endl;
			baddata = true;
		}
		

		else if (!cin.good())
		{
			cin.clear();
			cin.ignore(numeric_limits<streamsize>::max(), '\n');
			cout << "I could not decifer your input as a binary value" << endl;
			baddata = true;
		}
	} while (baddata);
	
		return n;
}
void bin_dec(long long n)
{
	double num = 0;
	double rem;
	int i = 0;
	
	

	
	while (n != 0)
	{
		
		rem = n % 10;
		n /= 10;
		num += (rem)*pow(2, i);
		++i;
	}
	cout << "The decimal value is: " << num << endl;
}

void test_bin(long long n)
{


	long long ans;
	while (n != 0 && n != 1)
	{
		ans = n % 10;
		if (ans > 1)
		{
			n %= 10;

		}
		else
			cout << "That is not a binary number" << endl;
	}


}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
bool is_binary( long long n )
{
    if( n < 0 ) return false ;
    if( n < 2 ) return true ;
    return n%10 < 2 && is_binary( n/10 ) ;
}

long long get_binary()
{
    std::cout << "binary number? " ;
    long long n ;

    if( std::cin >> n && is_binary(n) ) return n ;

    std::cerr << "badly formed binary number\n" ;
    std::cin.clear() ; // clear possible error state
    std::cin.ignore( 1000000, '\n' ) ; // discard this line of input
    return get_binary() ; // try again
}
What does a function prototype look like for bool, and how would you I call it in main?
Nevermind I figured it out, thanks for all the help guys.
Topic archived. No new replies allowed.