简体   繁体   中英

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.

所有位都已在x中设置-因此对其执行任何|=操作都不会更改。

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

x &= y;

我想你的意思是从

unsigned short x = 0x0000;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM