-1

Suppose x is unsigned int

Then is x << n equal to x * 2n

I know it's true for signed integers.

Is x * 15 equal to x << 4 - x?

chqrlie
  • 131,814
  • 10
  • 121
  • 189
Shabaz
  • 9
  • 1

1 Answers1

1

This answer is for the C language. There seems to be subtle differences in the C++ specification for this particular question.

If x is unsigned and if n >= 0 and less than the number of value bits in the type of x, x << n is indeed the same as multiplying x by the n-th power of 2.

If this computation overflows, the result will reduced modulo the largest value for the type of x plus 1.

If x is signed, it must be non-negative the result must not overflow or you will get undefined behavior. A common case of undefined behavior on 32-bit architectures is this:

unsigned x = 1 << 31;   /* undefined behavior: 1 is signed, 31 is too large */

The correct version is:

unsigned x = 1U << 31;   /* correct on 32 bit architectures */

Incidentally, Since C++14, the C++ Standard has a specific provision for this very case:

the value of a << b is a times 2b if it is representable in the unsigned version of the return type (which is then converted to signed: this makes it legal to create INT_MIN as 1 << 31), otherwise the behavior is undefined.

Regarding your second question, is x * 15 equal to x << 4 - x?

The answer is no because x << 4 - x is parsed as x << (4 - x).

If you parenthesize your expression, then indeed x * 15 == (x << 4) - x.

Note however that it is not correct for signed values, because the intermediary result x << 4 could overflow for large values of x for which the result of x * 15 would not.

chqrlie
  • 131,814
  • 10
  • 121
  • 189
  • In C++, there is a strange special provision to avoid making 1<<31 UB. – Marc Glisse May 01 '18 at 07:41
  • They made it implementation-defined because Howard Hinnant was sick of having to mangle his code to avoid the UB – M.M May 01 '18 at 08:28
  • @MarcGlisse: Did C++ ditch the non 2's complement architectures and padding-bits and trap-values alike? How much sense does it make to keep these anyway? – chqrlie May 01 '18 at 08:55
  • 2
    http://en.cppreference.com/w/cpp/language/operator_arithmetic#Bitwise_shift_operators (see the "since C++14" part). Or check the standard directly. – Marc Glisse May 01 '18 at 09:21