Arithmetic bit-shift on a signed integer

前端 未结 6 1434
别跟我提以往
别跟我提以往 2020-11-22 07:36

I am trying to figure out how exactly arithmetic bit-shift operators work in C, and how it will affect signed 32-bit integers.

To make things simple, let\'s say we w

6条回答
  •  天涯浪人
    2020-11-22 07:42

    As of c++20 the bitwise shift operators for signed integers are well defined.

    The left shift a< is equivalent to a*2^b modulus 2^N where N is the number of bits in the resulting type. In particular 1<<31 is in fact the smallest int value.

    The right shift a>>b is equivalent to a/2^b, rounded down (ie. towards negative infinity). So e.g. -1>>10 == -1.

    For some more details see https://en.cppreference.com/w/cpp/language/operator_arithmetic .

    (for the older standards see the answer by Matthew Slattery)

提交回复
热议问题