Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional check for "i == (2^8)" fails when i is 512?

Tags:

c

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.

like image 490
Sandeep Avatar asked Jul 23 '12 07:07

Sandeep


3 Answers

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) ) ...
like image 93
Guy Adini Avatar answered Oct 17 '22 04:10

Guy Adini


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.

like image 26
Felice Pollano Avatar answered Oct 17 '22 05:10

Felice Pollano


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.

like image 45
Hasturkun Avatar answered Oct 17 '22 05:10

Hasturkun