Search code examples
c++xor

C++ Right Shift, XOR problems


I have this sample code:

#include "stdafx.h"
#include "stdio.h"
#include "stdlib.h"
#include "math.h"
#ifndef uint32
#define uint32 unsigned long int
#endif
#define L(a) printf("\n%x >> 1 = %x", a, a>>1)
int _tmain(int argc, _TCHAR* argv[])
{
    uint32 a = 2941362065;
    uint32 b = 509727776;
    uint32 c = a ^ b;
    L(a^b);
    printf("\n%x >> 1 = %x", c , c>>1);
    return 0;
}

My problem is that L(a) returns

b1304bb1 >> 1 = a0617581

while

printf("\n%x >> 1 = %x", c , c>>1);

returns

b1304bb1 >> 1 = 589825d8

The last value is the one that appears to be correct as the windows calculator returns it. This code is running on WinXP 32. Any ideas?


Solution

  • You are getting bitten by the way macros in C work. The right shift has a higher precedence than xor, so it will happen first. You should surround every instance of a in the definition of L with parentheses.