7

Why are there no bit shifting opcodes in Ethereum? What's the fastest and cheapest way (in terms of gas) to implement them?

5
x >> y = x / 2**y
x << y = x * 2**y
  • 2
    This answer can be improved if some context and description is added to explain it a little further for general audiences :) – Jeff Coleman Jan 22 '16 at 1:10
  • 5
    also, is the answer to "why" A) it's not needed in EVM, or B) higher level languages are expected to provide such functions, or C) everyone that needs it should implement it? – eth Jan 22 '16 at 1:42
5

I don't know what was the rationale behind not including bit shifting opcodes in the EVM, but (for most of the cases) they can definitely be emulated with multiplication and division. Having dedicated opcodes for them would make them faster.

  • Left shift (x << y) is equivalent to: x * (2 ^ y)
  • Right shift (x >> y) is equivalent to: x / (2 ^ y)

(Where 2 ^ y means power, usually written as 2 ** y in programming languages.)

These are known as logical shifts. For arithmetic shifts it can produce different results to what's expected.

Luckily in the EVM there is signed (SDIV) and unsigned division (DIV) so both cases of right shifts can be implemented.

If you are looking at Solidity, I'm not entirely sure which one it will use in the case of right shift.

3

Shift opcodes - SHL, SHR, SAR - are a planned addition of Constantinople (expected in 2019).

See the relevant EIP here: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-145.md

  • 1
    Thanks, an answer of this sort can be accepted when the EIP is implemented and more details are provided, for example how to use the new opcodes including higher-level language/s. – eth Nov 10 '18 at 23:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.