Circular shift in c

后端 未结 4 1932
广开言路
广开言路 2020-12-05 02:54

How does the following code work and what do the variables mean:

y = (x << shift) | (x >> (sizeof(x)*CHAR_BIT - shift));

I foun

4条回答
  •  甜味超标
    2020-12-05 03:13

    This works with unsigned types only. In the case with a signed negative number most left bits will be substituted by the value of most significant bit (with 1-s) by the right-shift operator (">>")

    I'd write it like this:

    y = (x << shift) | ( (x >> (sizeof(x)*CHAR_BIT - shift)) & (0x7F >> (sizeof(x)*CHAR_BIT - shift) );
    

    In here before "|" operator we do confirm that first n bits ( n = sizeof(x)*CHAR_BIT - shift) are zeroed. We also assume, that x is short (2-bytes long). So, it's also type-dependent.

提交回复
热议问题