Simple question (exponents)

Hi! I am new to this forum and C++, so my question will probably be very easy to answer for you: (Please note it is not done yet)

I am translating from TrueBASIC a program which will translate binary to interger. Part of it includes having 2 be to the xth power. I have Visual C++ 5, and it says iy should be in this format:

answer = number^exponent (Exactly as in BASIC)

Now, I have already tried this but I cannot get it to work at all. Here is the code:




#include <iostream.h>
#include <string.h>

int main()
{
     int answer, binary, x, number;

     x = -1;
     answer = 0;

     cout << "This program will convert binary numbers into ordinary numbers."<<endl<<endl<<endl<<"What binary number do you want to convert?"<<endl<<"(Please type numbers in one at a time STARTING FROM RIGHT TO LEFT)"<<endl<<"When done, please press any number above 1"<<endl;
     cin >> binary;
     while (binary < 2)
     {
          x = x + 1;
          if (binary == 0){
               cout << "0"<<"           ";}
          else{
               cout << "1"<<"           ";
               number = 2^x;  //here is the problem!
               answer = answer + number;}
          cout << answer<<endl;
          cin >> binary;
     }
     cout <<endl<<endl<<endl<<"The final answer is:  "<<answer<<endl;
return 0;
}


Is there anything I should include? I have already tried math.h, yet it does not solve the problem.
LVL 1
SpongeyAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

efnCommented:
You have been led astray by whoever told you you could use the same kind of exponentiation expressions as in BASIC.

In C and C++, ^ is the bitwise exclusive-or operator and there is no exponentiation operator.

You can use the library facility pow to raise a number to a specified power.  It operates on doubles (a floating-point type) and returns a double.

See:

http://www.acm.uiuc.edu/webmonkeys/book/c_guide/2.7.html#pow

You will need to include math.h to use it.

For powers of 2, you could also use the left-shift operator <<.  Shifting 1 left n places gives you 2 to the nth power.
0
n_fortynineCommented:
you can use double pow(double base, double nth) from math.h
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
n_fortynineCommented:
sorry double (double, int)
0
Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

n_fortynineCommented:
actually both'll be fine
0
Mayank SAssociate Director - Product EngineeringCommented:
>> number = 2^x;  

Change it to:

number = pow ( 2, x ) ;

And include <math.h> in your program.

Mayank.


0
SalteCommented:
The ^ operator is the XOR or exclusive OR operator in C++ and C.

There is no operator for exponent.

However, since you only use powers of 2 you shouldn't use exponents at all.

To translate binary to integer it is simply a matter of reading the value in radix 2.

The easy way is this:

int x = strchr("11101",0,2);

x will then have the value 0x0000001d

0x1d in hex is 0001 1101 in binary and is the same as the string read.

If you want to do it the hard way yourself you can use the << operator to shift a value up one bit (same as multiply by 2):

if x = 0x1d == 11101 in binary then:

x << 1 == 0x3a == 111010 in binary
(x << 1) | 1 == 0x3b == 111011 in binary
(x << 1) | 0 == 0x3a also.

This way you can build up the value:

int x = 0;

while (true) {
   switch (*s) {
   case '0':
      x <<= 1;
      ++s;
      continue;
   case '1':
      x = (x << 1) | 1;
      ++s;
      continue;
   }
   break;
}

after this loop x will have the value reflected by the binary input. if s was "1011110110101110" before the loop then s will point to "" at the end (s is modified) and x is 0xbdae after.

You can use pow(x,y) function to computer power but in this case that is silly since pow computes power using exp(x) and log(x) functions like so:  pow(x,y) == exp(y*log(x)) if x is not 0 and pow(0,y) == 0 if y is not 0 and pow(0,0) is undefined, I think it returns 'not a number' but not sure about that one.

You can also define a pow(x,n) for an unsigned int n as follows:

double pow(double x, unsigned int n)
{
   double y = n & 1 ? x : 1.0;
   double f = x * x;
   while (n >>= 1) {
      if (n & 1)
         y *= f;
      f *= f;
   }
   return y;
}

Then you can define pow(x,n) for a signed int n as follows:

double pow(double x, int n)
{
   return n >= 0 ? pow(x,(unsigned int)n) : 1.0/pow(x,(unsigned int)-n);
}

You can also define pow(x,n) for complex values of x and n easily using the various overloads for pow(x,n).

None of those are useful for extracting bits though since they do a lot of computation and then converting double to int. The shift instructions are far more direct and immmediate. They're also a lot faster.

Alf
0
garavindbabuCommented:
i think u can use "pow" functions as pow(2,x).where by u can have the binary
0
SalteCommented:
Yes, pow(2,x) works but is extremely inefficient:

pow(2,x) is the same as exp(x * log(2)).

so:

step 1. convert x from int to double.
step 2. compute log(2).
step 3. multiply x with log(2).
step 4. compute exp(x * log(2)).
step 5. convert the result from step 4 to int.

all that when you can do a simple (1 << 5) to compute pow(2,5) as int?

No, do NOT advice anyone to use pow() to get binary. That is a very misguided advice.

Alf
0
MafaldaCommented:
>>>> int x = strchr("11101",0,2);
Salte, I think you used the wrong function.
Where is strchr() defined ?
0
Mayank SAssociate Director - Product EngineeringCommented:
Mafalda,

strchr () is defined in string.h itself.

Mayank.
0
SalteCommented:
err...I meant strtol() not strchr....

Sorry about that...


int x = strtol("11101",0,2);

just a bit too quick there writing the function - to my defense I can add that I was in a hurry when I wrote it.

Alf
0
SalteCommented:
strtol() is defined in #include <cstdlib> or in #include <stdlib.h>.

This is C's standard library, not the same as C++'s standard library although it is a part of C++'s standard library if you use <cstdlib>.

Alf
0
Mayank SAssociate Director - Product EngineeringCommented:
>> strchr("11101",0,2);

Ya! strchr () searches for a character in a string, takes 2 arguments, the string and the character being searched for. I overlooked your statement when I told Mafalda about strchr () being in string.h. Anyways, strtol () is Ok for the purpose.

Mayank.
0
tinchosCommented:
No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:

Split points between efn & Salte

Please leave any comments here within the next seven days.

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

Tinchos
EE Cleanup Volunteer
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C++

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.