问题
Is char c2=i1<<8>>24; valid C syntax? (Where i1 is and unsigned integer) Additionally, will it yield the result of shifting i1 8 bits left and 24 bits right respectively? I am unpacking a char previously stored in i1, along with three other chars. Code below:
unsigned char b3 = 202;
unsigned char b2 = 254;
unsigned char b1 = 186;
unsigned char b0 = 190;
...
unsigned int i1=202;
i1=i1<<8;
i1=i1+254;
i1=i1<<8;
i1=i1+186;
i1=i1<<8;
i1=i1+190;
...
char c1=i1>>24;
char c2=i1<<8>>24;
回答1:
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.)
回答2:
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.
回答3:
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;
来源:https://stackoverflow.com/questions/32832262/bitwise-shift-left-and-right-in-the-same-statement