-1

I understand that offset operators perform multiplication and division on the number. So when I have 80 >> 3, I translate it by dividing 80 by two, three times. And when I see this 80 <<< 3, I translate it by multiplying 80 by two, three times. But I didn't understand correctly, because I don't understand that: 9 <<< 99 = 72, because I expected 9 multiplied by two, 99 times, so 9 * ( 2 ^ 99). But actually no, it doesn't work.... I've read different articles, but I still don't understand.

  • 1
    Possible duplicate of [why is 1>>32 == 1?](https://stackoverflow.com/questions/3170412/why-is-132-1) – Stephen C Jan 29 '19 at 04:09
  • You need to specify which programming language you are talking about. Behavior of operators is language specific. But for Java, see the linked question. – Stephen C Jan 29 '19 at 04:11
  • @StephenC I'm talking about Python and Node.js. –  Jan 29 '19 at 04:12
  • 1
    They behave differently. Javascript follows the Java model; see https://www.ecma-international.org/ecma-262/5.1/#sec-11.7. For python, the specification says `a << N` is equivalent to `a * pow(2, N)` ... truncated to an integer. – Stephen C Jan 29 '19 at 04:24
  • unless integer in your language is a 103-bit (or arbitrary precision) type, obviously 9*2^99 won't fit in the type and will overflow – phuclv Jan 29 '19 at 08:35

1 Answers1

1

The thing to remember about bit-shifting is, your values only have a finite number of bits, and (for primitive value-types at least) that number of bits is going to be less than 99.

In fact, if you compile your code with warnings enabled, you'll probably a see a warning like this:

`warning: shift count >= width of type [-Wshift-count-overflow]`

... that is the compiler telling you that what you're trying to do invokes undefined behavior. Most likely the value you are shifting is either 32 bits or 64 bits long (depending on your code and/or the computer you are compiling for), so shifting left by more bits than that isn't a valid thing to do.

Jeremy Friesner
  • 70,199
  • 15
  • 131
  • 234