I have reproduced a small part of a big programme trying to get the decimal of a binary number
int k=3;
int l=2;
int myinput;
void setup()
{
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop()
{
// put your main code here, to run repeatedly:
myinput=((pow(2,k))+(pow(2,l)));
Serial.print (k);
Serial.print(" ");
Serial.print (pow(2,k));
Serial.print(" ");
Serial.print (l);
Serial.print(" ");
Serial.print (pow(2,l));
Serial.print(" ");
Serial.println (myinput);
delay(5000);}
The result (myinput) comes out as 11.
the cube of 2 plus the square of 2 equals 12.
or am I missing something?
Mathematically speaking you are correct, but the code that has to use floating point arithmetic is only accurate up to 1 lup; that can cause havoc. If all you want to do is raise 2 to the power n, simply use (2<<(n)) and all will be fine (within the limitation of word lengths); so '(2<<(3))+(2<<(2))' will be perfectly fine.
JosAH:
If all you want to do is raise 2 to the power n, simply use (2<<(n)) and all will be fine (within the limitation of word lengths); so '(2<<(3))+(2<<(2))' will be perfectly fine.
For 2 to the power of n, you want (1<<(n)).
Example:
2 to the power of 3 is 8
1<<3 gives you 8
that's excellent thank you,
I don't quite understand how it works but it also includes 1<<(0) which gives me 1 so I can just use the numbers I have direct.
I am trying to make a shift register light a sequence of lights with an input which is the decimal equivalent of binary i.e. 1 2 4 8 16 etc and I have a number that increases by one as my reference so this works perfectly 1<<(n) to convert my "n" into a number for the shift register.
etc. It works because we are working in a base 2 system. Works for quick multiplication and division of numbers by 2. If you don't mind truncation of remainders.
Assumes unsigned numbers. If you used signed numbers as you got to the end you would mess everything up.
pow() returns a floating point number, and assigning a floating point number to an integer variable results in truncation, rather than rouding. And pow() uses a series based expansion so that it can handle fractional powers, so it probably comes up with something like 11.99999. Truncate that, and you get 11, rather than 12.
You can make your current code work using something like:
myinput=((pow(2,k))+(pow(2,l)))+0.5; // round
But, as other people have pointed out, pow() is really not what you want to do if you're using integers. And especially not for powers of 2...