Bitwise shift left and right in the same statement

后端 未结 3 1049
再見小時候
再見小時候 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.)

提交回复
热议问题