Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

Simple question (exponents)

Posted on 2003-03-16
14
Medium Priority
?
420 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
  • 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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Errors will happen. It is a fact of life for the programmer. How and when errors are detected have a great impact on quality and cost of a product. It is better to detect errors at compile time, when possible and practical. Errors that make their wa…
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 how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.
Suggested Courses

580 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