简体   繁体   中英

Doubts on bit-shifting behavior

I would like to clear some doubts on bit-shifting:

  1. Using unsigned int :

    unsigned int i = 500;
    i << 24;

    As far as I know this causes unsigned int to overflow, is this perfectly fine?

C++17 (8.5.7/2) - The value of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are zero-filled. If E1 has an unsigned type, the value of the result is E1 × 2^E2, reduced modulo one more than the maximum value representable in the result type.

  1. Is using right-shift on signed int perfectly fine as long as I am shifting less than '32 bit' because 'int' is 32 bits on my platform.

    int i = 500;
    i >> 31;

Is that an overflow?

C++17 (8.5.7/3) The value of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a non-negative value, the value of the result is the integral part of the quotient of E1/2^E2.

  1. is this perfectly fine?

    Yes. i will become 4093640704 , in hexadecimal 0xf4000000 .

  2. Is that an overflow?

    No. It is a right shift (division-like operation), so i will become zero.

Note, that the rules about shift are very likely to change. Currently, several cases are undefined behavior or implementation defined. As the next standard will require two's complement arithmetic, the rules about shifting will be relaxed: the only undefined behavior will be, if the shift amount is larger or equal than the types' width. Here are the current draft rules: link .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM