Bitwise shift left and right in the same statement

后端 未结 3 1046
再見小時候
再見小時候 2021-01-25 12:49

Is char c2=i1<<8>>24; valid C syntax? (Where i1 is and unsigned integer) Additionally, will it yield the result of shifting i1

相关标签:
3条回答
  • 2021-01-25 13:25

    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.)

    0 讨论(0)
  • 2021-01-25 13:26

    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.

    0 讨论(0)
  • 2021-01-25 13:49

    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;
    
    0 讨论(0)
提交回复
热议问题