URGENT!!! Write a program that produces the binary equivalent of a non-negative integer input by the user.

Pages: 123
I have a question for my coding class But I have no Idea how to do it. or where to start. I am not sure what type of function to use. and so on
The binary number system is a base 2 number system. There are only two digits used (0 and 1)
and the digits of any binary number, going from right to left, represents the number of each
successively higher power of two that is part of the original binary number. For example: The binary
number 11001 means one 1, no 2’s, no 4’s, one 8, and one 16 (which adds up to 25, decimal). Note: 1=2^0, 2=2^1, 4=2^2, 8=2^3, and 16=2^4.

To convert a decimal number to its binary number equivalent, repeatedly divide the decimal number
by two, until the quotient is zero, keeping track of the remainder digit at each division step – the
remainder digits are the binary digits of the binary number representation going from right-to-left.
Example: Convert 22 decimal to binary.
22/2=11, remainder = 0
11/2=5, remainder = 1
5/2=2, remainder = 1
2/2=1, remainder = 0
1/2= 0, remainder = 1
Done, since the quotient = 0.
So, 22 decimal = 10110 binary.

Write a program that produces the binary equivalent of a non-negative integer input by the user. Use the algorithm described above to generate the binary digits in reverse order.
Note that this is a repetitive process, but the binary digits (the remainders) are determined “backwards”. So that you can display the binary digits in the correct order, make use of a string and the string concatenation operator, +. Initialize an accumulator string to a blank string (i.e., initialize to “”) and then repeatedly concatenate the appropriate remainder bits to the string. (Note: Concatenate ‘1’ or ‘0’ characters to the accumulator string, not 1 or 0 integer values.) Be careful to concatenate the remainder bits into the string in the proper way so that when you are done, the string contains the remainder bits in the correct order. Remember: The concatenation operator is not commutative (i.e., string1 + string2 does not necessarily equal string2 + string1.) Then display the binary equivalent string.
Here is an example of what output should look like from running your program (user input is shown in bold):
Enter a positive integer: 22
22 decimal = 10110 binary
Last edited on
Use the algorithm described above … Note that this is a repetitive process … make use of a string and the string concatenation operator, + … Concatenate ‘1’ or ‘0’ characters to the accumulator string, not 1 or 0 integer values … concatenate the remainder bits into the string in the proper way … Then display the binary equivalent string.
I have no Idea how to do it

What part of the tidy, accurate, exhaustive aforementioned instruction list is not clear?
-_____- I do not really know how to start this. I figure do a cout<<"Enter a positive integer: "; then a cin>>decimal; then I don't really know how to approach the strings I am bad at those. Do you know how do string code for this?
it tells you.
basically
string s; //empty string

s += letter; //appends to the string. so if you do this twice with '1' and then '2' you get "12" as a string.

the guts of what you are trying to do is something like this:

unsigned int p = pow(2,64);
char bl[] = {'0','1'};
while (p)
{
s+= bl[value&p!=0];
p = p>>1;
}

the instructions make you do the above in a more convoluted way for some reason, but the string logic will be similar: figure out whether you want a 1 or a 0 and put that into the string at the desired location. Iterating backwards makes no real sense to me, but its the same idea with more work. I provide leading zeros, but hex and binary usually do show leading zeros when output.
Last edited on
Im sorry could you please just show me the answer to the problem in like a c++shell and then I can ask questions on things I don't understand.
no. But if you show us what you wrote with a question, I will try to help you, and others will as well.

I can make the above work in shell. but I won't do it backwards with all the carry nonsense. Your professor is asking for, in math terms, how to take the area of a square with calculus. I will leave the annoying approach to you; below is the direct and simple solution to the actual question (stringify uint into binary-text). Doing it in reverse with all the clutter will be good practice (even if doing a bad algorithm).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <string>
#include<cmath>
#include <iostream>
using namespace std;
int main(int argc,char **argv)
{
	
uint64_t p = pow(2,63);
char bl[] = {'0','1'};
string s;
uint64_t value = 255;
while (p)
{
s+= bl[ (value&p)!=0]; //this is what you asked: how to build the string.  
//which is : make a decision what letter to add to the string, and do it. 
p = p>>1;
}
cout << s << endl;
  return 0;	
}


output: 0000000000000000000000000000000000000000000000000000000011111111
which is 255 (8 bits of 1s).
Last edited on
So if I wanted to make this calculate the code for any given number I could change the uint64_t into cout and cin function? also the pow(2,63) can that be changed somehow as well?
it already works on any number, read in value instead of just setting it to a fixed number.

no, you cannot change an integer into a print statement.

what would you like to change the power function to? You can make it a constant. it is ‭9223372036854775808‬ULL if you prefer that.

What I mean is I want there to be a prompt that asks for a number then it does the problem. would I just do count enter number the cin it to the uint64_t value? could you show me how the read in function would fit in?
Last edited on
you want to say
cout << "words about typing in a value\n";
cin >> value;
between line 11 and 12.

its probably cleaner to set value = 0 initially after doing that, but it makes no real difference.

I highly advise you not to turn my code in as yours, if that is where you are going. I did not follow his convoluted approach, and I suspect that is desired.
Last edited on
Could you please show me how to then start the code to have it cout all of its work on how it got each 1 and 0?
No. Its time for you to try writing some code on your own, and posting it when you can't see what you did wrong if it does not work.
Ok so what I have is this. What I want is for when it goes it every time it shows a number say I put in 22 I want it to say 22/2=11 remainder 0 then next line say 11/2=5 remainder 1 and so on. What I cant figure out is how to make this "22" or value float down every time. Also I don't want the equation to start at massive numbers I just want it to show the value be the max then go down from there. I don't want to see all of the extra 0s too.

#include <string>
#include<cmath>
#include <iostream>
using namespace std;
int main(int argc,char **argv, int val)
{
float value;
uint64_t p = pow(2,63);
char bl[] = {'0','1'};
string s;
cout<<"enter a positive integer: ";
cin>> val;
while (p)
{
s+= bl[ (val&p)!=0];
cout<<val<<"/ "<<value<<" = "<< p<< " remainder ="<<s<<endl;
value=val/2^p;
p = p>>1;
cout<<p<<endl;
}
cout <<"Done, since the quotience = 0."<<endl;
cout<< "so, "<< val<<" decimal = "<< s << endl;
return 0;

}

this is what it outputs

enter a positive integer: 22
22/ 8.89736e+29 = 9223372036854775808 remainder =0
4611686018427387904
22/ 9.22337e+18 = 4611686018427387904 remainder =00
2305843009213693952
22/ 4.61169e+18 = 2305843009213693952 remainder =000
1152921504606846976
22/ 2.30584e+18 = 1152921504606846976 remainder =0000
576460752303423488
22/ 1.15292e+18 = 576460752303423488 remainder =00000
288230376151711744
22/ 5.76461e+17 = 288230376151711744 remainder =000000
144115188075855872
22/ 2.8823e+17 = 144115188075855872 remainder =0000000
72057594037927936
22/ 1.44115e+17 = 72057594037927936 remainder =00000000
36028797018963968
22/ 7.20576e+16 = 36028797018963968 remainder =000000000
18014398509481984
22/ 3.60288e+16 = 18014398509481984 remainder =0000000000
9007199254740992
22/ 1.80144e+16 = 9007199254740992 remainder =00000000000
4503599627370496
22/ 9.0072e+15 = 4503599627370496 remainder =000000000000
2251799813685248
22/ 4.5036e+15 = 2251799813685248 remainder =0000000000000
1125899906842624
22/ 2.2518e+15 = 1125899906842624 remainder =00000000000000
562949953421312
22/ 1.1259e+15 = 562949953421312 remainder =000000000000000
281474976710656
22/ 5.6295e+14 = 281474976710656 remainder =0000000000000000
140737488355328
22/ 2.81475e+14 = 140737488355328 remainder =00000000000000000
70368744177664
22/ 1.40737e+14 = 70368744177664 remainder =000000000000000000
35184372088832
22/ 7.03687e+13 = 35184372088832 remainder =0000000000000000000
17592186044416
22/ 3.51844e+13 = 17592186044416 remainder =00000000000000000000
8796093022208
22/ 1.75922e+13 = 8796093022208 remainder =000000000000000000000
4398046511104
22/ 8.79609e+12 = 4398046511104 remainder =0000000000000000000000
2199023255552
22/ 4.39805e+12 = 2199023255552 remainder =00000000000000000000000
1099511627776
22/ 2.19902e+12 = 1099511627776 remainder =000000000000000000000000
549755813888
22/ 1.09951e+12 = 549755813888 remainder =0000000000000000000000000
274877906944
22/ 5.49756e+11 = 274877906944 remainder =00000000000000000000000000
137438953472
22/ 2.74878e+11 = 137438953472 remainder =000000000000000000000000000
68719476736
22/ 1.37439e+11 = 68719476736 remainder =0000000000000000000000000000
34359738368
22/ 6.87195e+10 = 34359738368 remainder =00000000000000000000000000000
17179869184
22/ 3.43597e+10 = 17179869184 remainder =000000000000000000000000000000
8589934592
22/ 1.71799e+10 = 8589934592 remainder =0000000000000000000000000000000
4294967296
22/ 8.58993e+09 = 4294967296 remainder =00000000000000000000000000000000
2147483648
22/ 4.29497e+09 = 2147483648 remainder =000000000000000000000000000000000
1073741824
22/ 2.14748e+09 = 1073741824 remainder =0000000000000000000000000000000000
536870912
22/ 1.07374e+09 = 536870912 remainder =00000000000000000000000000000000000
268435456
22/ 5.36871e+08 = 268435456 remainder =000000000000000000000000000000000000
134217728
22/ 2.68435e+08 = 134217728 remainder =0000000000000000000000000000000000000
67108864
22/ 1.34218e+08 = 67108864 remainder =00000000000000000000000000000000000000
33554432
22/ 6.71089e+07 = 33554432 remainder =000000000000000000000000000000000000000
16777216
22/ 3.35544e+07 = 16777216 remainder =0000000000000000000000000000000000000000
8388608
22/ 1.67772e+07 = 8388608 remainder =00000000000000000000000000000000000000000
4194304
22/ 8.38862e+06 = 4194304 remainder =000000000000000000000000000000000000000000
2097152
22/ 4.19432e+06 = 2097152 remainder =0000000000000000000000000000000000000000000
1048576
22/ 2.09716e+06 = 1048576 remainder =00000000000000000000000000000000000000000000
524288
22/ 1.04859e+06 = 524288 remainder =000000000000000000000000000000000000000000000
262144
22/ 524299 = 262144 remainder =0000000000000000000000000000000000000000000000
131072
22/ 262155 = 131072 remainder =00000000000000000000000000000000000000000000000
65536
22/ 131083 = 65536 remainder =000000000000000000000000000000000000000000000000
32768
22/ 65547 = 32768 remainder =0000000000000000000000000000000000000000000000000
16384
22/ 32779 = 16384 remainder =00000000000000000000000000000000000000000000000000
8192
22/ 16395 = 8192 remainder =000000000000000000000000000000000000000000000000000
4096
22/ 8203 = 4096 remainder =0000000000000000000000000000000000000000000000000000
2048
22/ 4107 = 2048 remainder =00000000000000000000000000000000000000000000000000000
1024
22/ 2059 = 1024 remainder =000000000000000000000000000000000000000000000000000000
512
22/ 1035 = 512 remainder =0000000000000000000000000000000000000000000000000000000
256
22/ 523 = 256 remainder =00000000000000000000000000000000000000000000000000000000
128
22/ 267 = 128 remainder =000000000000000000000000000000000000000000000000000000000
64
22/ 139 = 64 remainder =0000000000000000000000000000000000000000000000000000000000
32
22/ 75 = 32 remainder =00000000000000000000000000000000000000000000000000000000000
16
22/ 43 = 16 remainder =000000000000000000000000000000000000000000000000000000000001
8
22/ 27 = 8 remainder =0000000000000000000000000000000000000000000000000000000000010
4
22/ 3 = 4 remainder =00000000000000000000000000000000000000000000000000000000000101
2
22/ 15 = 2 remainder =000000000000000000000000000000000000000000000000000000000001011
1
22/ 9 = 1 remainder =0000000000000000000000000000000000000000000000000000000000010110
0
Done, since the quotience = 0.
so, 22 decimal = 0000000000000000000000000000000000000000000000000000000000010110

Exit code: 0 (normal program termination)
Last edited on
ok, that is the right answer for 22.

if you want it to start at 2 instead of 2^63, then you need to reverse the logic.

if you want to cut leading zeros, you can just not add the zeros to the string until you get a '1'. just put an extra Boolean in there, and when you get your first '1' set it to true and start building the value.

if you want to start at the most significant digit, you need some math to figure out what that is. Maybe the log base 2 of 22 gets you how many binary digits it has... or very close, perhaps off by one? Do you understand this, and why?
after that you can change pow(2,63) to pow(2, math expression) and it will magically bypass the leading zeros and do less work.

the 2 things are not compatible. If you are working it from the left, and worried about leading zeros, then you are not starting at 2, which is working on it from the right. if you want to work on it from the right, you don't need all that junk about the leading digits, it happens naturally, but then you have to reverse the output and do what your prof said in the text. You seem to be trying to work both ends at once.

Your assignment reads:
Use the algorithm described above to generate the binary digits in reverse order. He wants you to do it his weird way, not going forwards. Ill say it again, you were supposed to learn from the forward example and code your own reversed example as per his instructions.

% is effectively remainder.
while(value)
{
r = value%2;
value/=2;
make a decision here, and add the right letter to s. same as I did going forwards, decide whether you need a '1' or a '0' and append it.
}
this is what he wants. and after all that you have gone and made s backwards, so you have to reverse it, /facepalm. So then you need to do that

...add more code to reverse string because you did it backwards. or as suggested, find a way to put them into the string in the right way. not sure but it sounds like he wants you to make a new string and put the previous string on it each time, to ensure the maximum number of variables and extra copies possible are used to be as inefficient as possible.
something like temp = "0" + realstring; //force the new digit on the front side.
realstring = temp; //so if you have 0, then 1, then 1, you get 0, then 01, then 011 instead of 110.
Last edited on
1
2
3
4
string binary( unsigned n )
{
   return ( n >> 1 ? binary( n >> 1 ) : "" ) + "01"[ n & 1 ];
}
I'm going to stick to the simple programming concepts that the assignment hints at. I suspect that you haven't yet seen some of the methods used by the solutions given so far.

You don't need floats for this. Just use unsigned ints.

There are two important things to know about unsigned (and integer) math in C++
1. The result of dividing two ints is an int.
2. The remainder function is %

Here is a program that prompts you for a number and then prints the quotient and remainder of num/2. Try using this as a starting point to get all the binary digits.
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <string>
using namespace std;

int main()
{
    unsigned num;
    cout << "Enter a number: ";
    cin >> num;
    cout << num << " / 2 = " << num/2 << '\n';
    cout << "remainder = " << num % 2 << '\n';
    return 0;
}

I have a few questions:
Jonnin can you use simpler terms or be more direct about what needs to happen. I understand you are frustrated trying to explain this to me but I am super stupid so I don't understand what you are saying or how to do it. Are you by chance an adult? A prof maybe retired or something? You are giving me the vibes that teachers give off. Especially your diction when you try to explain something. It's not like someone who types to be concise. The only exception is some occasional typos where you don't put a apostrophe or you start a sentence with a lowercase--but since they are so few maybe they just slip through your attention when you're typing--. You expect people to know things because Idk just like teachers do. Either way just assume I don't know how to do what you are saying. And I am very grateful for you helping me since my college is closed down and there isn't anyway to get help other than here. So thanks again!

>Boolean in there, and when you get your first '1' set it to true and start building the value.
what is Boolean? how do I set a boolean? do you mean like a do loop or something? Oh wait never mind I looked it up and you mean a True False thing. But it's its own code thing which I don't know how to program.
>Maybe the log base 2 of 22 gets you how many binary digits it has... or very close, perhaps off by one? Do you understand this, and why?
no not really. log base 2 of 22 get 4.5 or five rounded up making the amount of numbers it has in its binary.
>after that you can change pow(2,63) to pow(2, math expression) and it will magically bypass the leading zeros and do less work.
so I already tried doing something like pow(2,value/2^something) but value is a float value so it wouldn't work in a int function I guess.
But what I think I'm getting from your previous comment is the mathematical equation I need is something like pow(2,base log 2 of val) but I don't know how to program that.
>, then you are not starting at 2, which is working on it from the right. if you want to work on it from the right, so are you saying something like start from the inputted value then... something maybe like pow(val,log base 2 of val)?? not really sure.
>Ill say it again, you were supposed to learn from the forward example and code your own reversed example as per his instructions.
ok so we kind of got it right at going forward since it did end up putting out the 10110. So now we have to try to do it backwards.
>r = value%2;//this says r--remainder?--=value remainder 2. Right? why do we need an r?
value/=2;
do you mean value/something=2?
>make a decision here, and add the right letter to s. same as I did going forwards, decide whether you need a '1' or a '0' and append it.//append could just say add to it.
You have lost me again in your explanation. Add what letter integer to s and why? Do you mean add r the remainder to s? Because s is already the binary code. I don't really catch what you mean. By adding the remainder to s do we somehow get the right amount of numbers Idk what you mean by this. Sorry.
I think what we want is a 0 because that is what we want first when it outputs the solution and its work. But if we are adding 0 to s literally adding zero does nothing so would we add 1?
>this is what he wants. and after all that you have gone and made s backwards, so you have to reverse it, /facepalm. So then you need to do that.
So he wants the:
while(value)
{
r = value%2;
value/s+1=2;
}
Even so where would I put this? to reverse s would it look like s-= bl[ (value&p)!=0]; instead of s+= bl[ (value&p)!=0];??
Also I get it I'm dumb I do not know what I am doing that is why I posted the question here.
>...add more code to reverse string because you did it backwards. or as suggested, find a way to put them into the string in the right way.
>not sure but it sounds like he wants you to make a new string and put the previous string on it each time, to ensure the maximum number of variables and extra copies possible are used to be as inefficient as possible.//Did you mean in it each time?
So basically I don't want to add more code to reverse the string cuz that sounds hard and I don't want to mess this up anymore. But both ways I don't know how to do that because I am bad at coding strings because I don't know how to do it correctly.
Also I don't know how to put a string inside another string. Just gonna state that.
>something like temp = "0" + realstring; //force the new digit on the front side.
realstring = temp; //so if you have 0, then 1, then 1, you get 0, then 01, then 011 instead of 110.
Ok so what is temp? Do I need to declare it in some sort of scope like as an int? and realstring? Thanks for explaining what each part of those two things do.


Lastchance
>return ( n >> 1 ? binary( n >> 1 ) : "" ) + "01"[ n & 1 ];
what is that? I get that n is the unsigned number that was my float value. But what does the rest do. I can't run it to see what it does since my code is jacked and there are problems that need to be fixed before I can run it.

Dhayden
> I suspect that you haven't yet seen some of the methods used by the solutions given so far.
That is very true.
>The remainder function is %... //line11 << num % 2 <<
Ok... So then why is there a 2 after %? If I put 22 into your code it puts out the remainder of 0 like it should. So I don't understand why there is a two there.
Also what I need is something that can loop this thing where it takes integer divided by two equals a new integer then the next like that new integer divided by two and so on. So if I loop my num as unsigned num it will make the integer update as it goes?

This is what my code looks like at the moment. It currently doesn't output anything because of it's errors:

#include <string>
#include<cmath>
#include <iostream>
using namespace std;
int main(int argc,char **argv, int val)//I guess this int val can go? Maybe?
{
unsigned num;
uint64_t p = pow(2,num/log base 2 of num);//One of the errors is that uint64_t was not declared in this scope
char bl[] = {'0','1'};
string s;
cout<<"enter a positive integer: ";
cin>> num;
while (p)
{
s+= bl[ (num&p)!=0];
cout << num << "/2 = " << num/2<< " remainder = "<< num % 2<<endl;

p = p>>1; //I don't remember what this does
cout<<p<<endl; //I think I can get rid of this right?
}
cout <<"Done, since the quotience = 0."<<endl;
cout<< "so, "<< val<<" decimal = "<< s << endl;
return 0;
}
Last edited on
No, well, as I'm currently semi-locked-down by the British government and having to work from home (not a trivial task), that was attention-diverting coffee-time code. A (slightly) more readable version would be:
1
2
3
4
string binary( unsigned n )
{
   return ( n < 2 ? "" : binary( n / 2 ) ) + "01"[ n % 2 ];
}


That is recursion, but you can, of course, do it with a loop.

However, note four things:
- to get the final digit at any stage use n % 2 (note the modulus operator %)
- to move on to the preceding binary digits use n / 2 (note the integer division, truncating where necessary)
- to get a character version of a numerical digit d there are many ways, including (char)('0' + d) or, as in my code, "01"[d] (the d'th character of the string "01")
- as you are putting in the preceding binary digit you need to prepend to your result string, not append to it, each time.
Last edited on
Here is your code, cleaned up a little and using things that you should know:
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
#include <string>
#include<cmath>
#include <iostream>
using namespace std;
int
main(int argc, char **argv)
{
    int num;
    string s;
    cout << "enter a positive integer: ";
    cin >> num;
    while (num) {
	if (num % 2 == 0) {
	    // num/2 has remainder 0
	} else {
	    // num/2 has remainder 1
	}
	cout << num << "/2 = " << num / 2 << " remainder = " << num % 2 << endl;
	num = num / 2;
	cout << num << endl;			 //I think I can get rid of this right?
    }
    cout << "Done, since the quotient = 0." << endl;
    cout << "so, " << num << " decimal = " << s << endl;
    return 0;
}

Let's look at line 13. num % 2 computes the remainder of num/2. So if this statement is true then you need to add code to add "0" to the string s. If the statement is false, then you need to add code (at line 16) to add "1" to s. See if you can write that code.
Thanks for cleaning it up dhayden. The only problem is then in the end it is supposed to say Done, since the quotient is 0.
So, ___ decimal = ____
And since num changes throughout the program it doesn't have anything to show at the end. And how can we get it to show the binomial code like it used to?
Last edited on
Pages: 123