Bitwise shift left and right in the same statement

冷暖自知 提交于 2019-12-02 09:02:14

The syntax is fine (although hard to read) and it will be parsed as c2 = (i1 << 8) >> 24.

So it will left shift i1 8 positions, thereby shifting the leftmost 8 bits off the lefthand edge, and then right shift the result 24 positions, thereby shifting the rightmost 16 bits off the righthand edge. If that's what you wanted, then you're good. I'd use parentheses to make it more readable.

If you're just going to convert that to a char, it's not obvious why you feel the need to remove the high-order bits (although it is true that there may be architectures in which int and char are the same size.)

Also, as noted by John Bollinger, it is possible for the end result to be larger than can fit in a char, which is not well defined in the common case that char is a signed type. (That will be true even if unsigned int is 32 bits, because you technically cannot assign a value greater than 127 to an 8-bit signed character.)

Yes, it is a valid syntax. It is a valid syntax also for signed int i1, in which case you can achieve filling the 'upper part' of the value with the bit from a chosen position.

As others have noted, it's valid syntax. You can achieve the effect that I believe is desired more understandably and portably with:

unsigned char c2 = (i1 & 0xff0000) >> 16;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!