Here is a small Program to print powers of 2 till 8. But it is not quitting after 8. Please explain the reason.
#include <stdio.h>
#include <unistd.h>
int main(void)
{
unsigned int i=1;
while(1) {
i = i<<1;
printf("i = %d\n",i);
if(i==(2^8))
break;
sleep(1);
}
printf("Exited While loop.. \n");
return 0;
}
The Loop is not Exiting when i = 2^8. My output is something like this:
i = 2
i = 4
i = 8
i = 16
i = 32
i = 64
i = 128
i = 256
i = 512 (Should have Exited here. But the program is continuing. Why?)
i = 1024
i = 2048
i = 4096....
EDIT :
Thanks for answering that ^ is an XOR operator. But now the below code is behaving strange. Please Explain.
#include <stdio.h>
int main(void)
{
if((2)^8 == 1<<8) {
printf("True.. \n");
} else {
printf("False..!!");
}
return 0;
}
The above function program prints true.
In C, the ^ operator means XOR (bitwise exclusive or).
To get 2 to the power of 8, you need to either use a loop (res *=2 in a loop), or round the pow function in math.h (note that the math.h function returns float - and therefore won't be equal to the integer).
The simplest method is the bitwise shift, of course.
About the edit section:
Welcome to the wonderful world of operator precedence. What happens is that == has higher precedence than ^, and therefore the conditional evaluates to 2^0, which is 2, which is true.
To make it work, you need to add parentheses:
if ( (2^8) == (1<<8) ) ...
The problem is that ^
is the Bitwise XOR operator, not raise to power. Let's explain 2^8
in bitwise format:
2 = 0010
8 = 1000
======== xor
10= 1010
so the result, applying xor bit by bit, is 10, that never happens so your loop never exits.
You can make your unit test working if you use pow(2,8)
and round to integer instead.
Another information, it is probably not the case in this example, but it is better to avoid the strict equality when working with floating point values, compare with an epsilon is better.
For your edit: Ensure the precedence with this:
if((2^8) == (1<<8))
this will return false, as expected.
2^8
is 2 XOR 8
, ie. 10, not 256. hence your loop doesn't stop. You probably want to check against either (1<<8)
or 256 specifically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With