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
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?
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.
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).
#include <string>
#include<cmath>
#include <iostream>
usingnamespace 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).
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?
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?
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.
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;
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.
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.
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;
}
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.
#include <string>
#include<cmath>
#include <iostream>
usingnamespace 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?