cdignam
cdignam

Reputation: 1453

Odd bit shifting behavior

I have the following C code which works:

int ex(unsigned int x) {
    int mask  = 0x55555555;
    int a = ((x >> 0) & mask );
    return a + ((x >> 1) & mask );
}

However, when I expand it to this, I get a different result:

int ex(unsigned int x) {
    int mask  = 0x55555555;
    int a = ((x >> 0) & mask );
    int b = ((x >> 1) & mask );
    return a + b;
}

What is the reason for this difference?

EDIT: Note, I'm compiling this for 32bit.

Upvotes: 28

Views: 1559

Answers (1)

alk
alk

Reputation: 70941

What is the reason for this difference?

The 1st snippet returns the result of adding two unsigneds with the result being (implicitly) converted to an int.

The 2nd snippet returns the result of adding two ints .


More on "The Usual Arithmetic Conversions":

Upvotes: 39

Related Questions