Blade3
Blade3

Reputation: 4360

Bit shifting in C

How would I do the following:

unsigned short x = 0xFFFF;
unsigned short y = 0xAE;

x |= y & 1;
x |= y & (1 << 1);
x |= y & (1 << 2);
x |= y & (1 << 3);
x |= y & (1 << 4);
x |= y & (1 << 5);
x |= y & (1 << 6);
x |= y & (1 << 7);
x |= y & (1 << 8);
x |= y & (1 << 9);
x |= y & (1 << 10);
x |= y & (1 << 11);
x |= y & (1 << 12);
x |= y & (1 << 13);
x |= y & (1 << 14);
x |= y & (1 << 15);
printf("%x", x); 

I want x to be equal to 0xAE, but it is still equal to 0xFFFF.

Upvotes: 1

Views: 206

Answers (4)

Paul Alexander
Paul Alexander

Reputation: 32367

There's no need to address each bit separately. The entire method can simply be reduced to

x &= y;

Upvotes: 3

Dave
Dave

Reputation: 3448

I think you meant to start with

unsigned short x = 0x0000;

Upvotes: 1

user257111
user257111

Reputation:

C is calculating the correct thing, since what you're doing here is taking y, ANDING it with each bit from 0 to 15 which does produce AE. However, then you're doing OxFF | oxAE which is oxFF. Try setting the assigment operator to &=. That will do 0xFF & 0xAE which is 0xAE.

Upvotes: 0

BrokenGlass
BrokenGlass

Reputation: 160882

All bits are set already in x - so any |= operation on it won't change that.

Upvotes: 3

Related Questions