Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   unable to explain arbit behaviou in addition (http://www.go4expert.com/forums/unable-explain-arbit-behaviou-addition-t1582/)

redgiant 9Oct2006 15:00

unable to explain arbit behaviou in addition
hi ,
please refer to the code below:


//-----code follows----------------------------


typedef unsigned char UInt8;
typedef unsigned short UInt16;
typedef unsigned long UInt32;
typedef unsigned long long UInt64;

int main(){
    UInt16 lowP = 8874, lowC =61008;
    UInt16 midP = 32566, midC =32848;
    UInt8 hiP = 0, hiC =0;

  //following two lines produce wrong output, note that we dont type cast midP and midC here
    UInt64 valP = lowP + (midP << 16) + (((unsigned long long)(hiP))<<32); //line 1
    UInt64 valC = lowC + (midC << 16) + (((unsigned long long)(hiC))<<32); //line 2

    //uncommenting below two lines instead of above two lines gives right result
  // UInt64 valP = lowP + (((unsigned long)midP) << 16) + (((unsigned long long)(hiP))<<32);
    //UInt64 valC = lowC + (((unsigned long)midC) << 16) + (((unsigned long long)(hiC))<<32);

    UInt64 diff = valC - valP;

    printf("valP:%x\n",valP >> 32);
    printf("valC:%x\n",valC >> 32);
    return 0;

//----------------code end-----------------------------

now when I run this program I get following output:

However instead if I comment two lines mentioned as line1 and line2 and uncomment two lines
following in the code above, I get the following output:

Can somebody explain this behaviour? why this behaviour incase we dont typecast to unsigned long. This does not happen with any values but some values.

redgiant 9Oct2006 15:06

Re: unable to explain arbit behaviou in addition
just to add I am using gcc from GNU for compiling above.

shabbir 9Oct2006 15:20

Re: unable to explain arbit behaviou in addition
Welcomte to G4EF.

Use the code block for better formatting.

Thats because when you shift 16 bits for some values it becomes zero but not for all and so you get
the output unpredicted.

redgiant 10Oct2006 10:27

Re: unable to explain arbit behaviou in addition
Shifting by 16bits may give me zero but most significant 32 bits are ffffffff. In the code hiC corresponds to most significant 32 bits and value of hiC is 0. How by not typecasting midC, we are affecting most significant 32 bits?

shabbir 10Oct2006 11:04

Re: unable to explain arbit behaviou in addition
If you dont type cast it becomes long by default but with type cast it become unsigned giving it an extra bit for positive numbers. Try type casting it to long and see if the result is same.

All times are GMT +5.5. The time now is 21:11.