?
Solved

Simple question (exponents)

Posted on 2003-03-16
14
Medium Priority
?
416 Views
Last Modified: 2012-05-04
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.
0
Comment
Question by:Spongey
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
  • 3
  • +4
14 Comments
 
LVL 15

Expert Comment

by:efn
ID: 8148903
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
 
LVL 4

Accepted Solution

by:
n_fortynine earned 200 total points
ID: 8149456
you can use double pow(double base, double nth) from math.h
0
 
LVL 4

Expert Comment

by:n_fortynine
ID: 8149590
sorry double (double, int)
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 4

Expert Comment

by:n_fortynine
ID: 8149594
actually both'll be fine
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8149734
>> number = 2^x;  

Change it to:

number = pow ( 2, x ) ;

And include <math.h> in your program.

Mayank.


0
 
LVL 12

Expert Comment

by:Salte
ID: 8150921
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
 
LVL 2

Expert Comment

by:garavindbabu
ID: 8151031
i think u can use "pow" functions as pow(2,x).where by u can have the binary
0
 
LVL 12

Expert Comment

by:Salte
ID: 8151140
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
 
LVL 6

Expert Comment

by:Mafalda
ID: 8151264
>>>> int x = strchr("11101",0,2);
Salte, I think you used the wrong function.
Where is strchr() defined ?
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8151305
Mafalda,

strchr () is defined in string.h itself.

Mayank.
0
 
LVL 12

Expert Comment

by:Salte
ID: 8151352
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
 
LVL 12

Expert Comment

by:Salte
ID: 8151358
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
 
LVL 30

Expert Comment

by:Mayank S
ID: 8151414
>> 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
 
LVL 9

Expert Comment

by:tinchos
ID: 9502105
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

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: SunnyDark
This article's goal is to present you with an easy to use XML wrapper for C++ and also present some interesting techniques that you might use with MS C++. The reason I built this class is to ease the pain of using XML files with C++, since there is…
Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.
Suggested Courses
Course of the Month12 days, 22 hours left to enroll

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question