Why are there no bit shifting opcodes in Ethereum? What's the fastest and cheapest way (in terms of gas) to implement them?
x >> y = x / 2**y x << y = x * 2**y
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)
2 ^ y means power, usually written as
2 ** y in programming languages.)
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.
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