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
?
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
?
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.