{"eip":145,"title":"Bitwise shifting instructions in EVM","description":"To Provide native bitwise shifting with cost on par with other arithmetic operations.","authors":["Alex Beregszaszi (@axic)","Paweł Bylica (@chfast)"],"status":"Final","type":"Standards Track","category":"Core","created":"2017-02-13","repo":"EIPs","label":"EIP-145","officialUrl":"https://eips.ethereum.org/EIPS/eip-145","sourceUrl":"https://github.com/ethereum/EIPs/blob/master/EIPS/eip-145.md","url":"https://eips.huatuo.xyz/eip-145/","tldr":{"en":"Added native SHL, SHR and SAR bit-shift opcodes to the EVM at 3 gas each, replacing costly multiply/divide-by-power-of-two workarounds.","ja":"EVM にネイティブのビットシフト命令 SHL、SHR、SAR を各 3 gas で追加し、コストの高い 2 の冪による乗算・除算の代用手段を置き換えた。","ko":"EVM에 네이티브 비트 시프트 옵코드 SHL, SHR, SAR를 각각 3 gas로 추가해, 2의 거듭제곱으로 곱하고 나누던 비싼 우회 방식을 대체했다.","zh":"为 EVM 原生添加 SHL、SHR 和 SAR 位移操作码，每个仅需 3 gas，取代了代价高昂的\"乘以或除以 2 的幂\"的变通写法。"},"tags":["evm","opcodes","core","constantinople","gas"],"explainers":{"en":{"lang":"en","tldr":"Added native SHL, SHR and SAR bit-shift opcodes to the EVM at 3 gas each, replacing costly multiply/divide-by-power-of-two workarounds.","tags":["evm","opcodes","core","constantinople","gas"],"related":[1013,1014],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/eip-145/","markdown":"## What problem does it solve?\n\nThe original EVM had AND, OR, XOR and NOT, but no way to shift bits. Contracts that packed several values into one 256-bit word, or decoded data byte by byte, had to fake a shift with arithmetic: `x * 2**n` for a left shift and `x / 2**n` for a right shift. The spec puts the cost of that workaround at about 35 gas, and it also meant more work for the node running it.\n\nEIP-145 adds three real shift instructions at the cheapest gas tier.\n\n## How it works\n\n| Opcode | Name | Result | Notes |\n| --- | --- | --- | --- |\n| `0x1b` | `SHL` | `(value * 2^shift) mod 2^256` | Logical left shift |\n| `0x1c` | `SHR` | `floor(value / 2^shift)` | Logical right shift, zero fill |\n| `0x1d` | `SAR` | `floor(value / 2^shift)` | Arithmetic right shift, `value` is signed, sign is preserved |\n\nEach pops two words: first the **shift amount**, then the **value**. That is the reverse of most arithmetic opcodes. It was chosen so that the value already on the stack can be shifted by pushing just the amount.\n\nEdge cases:\n\n- A shift of 256 or more gives `0` for `SHL` and `SHR`. For `SAR` it gives `0` for a non-negative value and `-1` (all ones) for a negative one.\n- `SAR` is not the same as signed division: `SDIV(-1, 2) == 0`, but `SAR(-1, 1) == -1`, because `SAR` rounds toward negative infinity.\n\nAll three cost 3 gas (the `verylow` tier). The opcodes went live in the Constantinople upgrade ([EIP-1013](/eip-1013/)).\n\n## Sample code\n\nRaw EVM, shifting `1` left by `0xff` bits:\n\n```text\nPUSH32 0x0000...0001   // value\nPUSH1  0xff            // shift amount (top of stack)\nSHL                    // -\u003e 0x8000...0000\n```\n\nIn Solidity, `\u003c\u003c` and `\u003e\u003e` compile to these opcodes when targeting Constantinople or later:\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\ncontract Packing {\n    // Pack two uint128 values into one storage word\n    function pack(uint128 hi, uint128 lo) external pure returns (uint256) {\n        return (uint256(hi) \u003c\u003c 128) | lo;          // SHL\n    }\n\n    function unpackHi(uint256 word) external pure returns (uint128) {\n        return uint128(word \u003e\u003e 128);               // SHR\n    }\n\n    function signedHalf(int256 x) external pure returns (int256) {\n        return x \u003e\u003e 1;                              // SAR, rounds toward -infinity\n    }\n}\n```\n\n## Things to know\n\n- Bytecode deployed before the fork is unaffected. Before Constantinople these byte values were simply invalid opcodes.\n- When compiling for a pre-Constantinople EVM version, compilers fall back to `MUL`/`DIV` with `EXP`, so the cheaper opcodes depend on your target setting.\n- In Solidity, `\u003e\u003e` on a signed integer rounds toward negative infinity, matching `SAR`. Do not assume it behaves like `/ 2` for negative numbers.\n"},"ja":{"lang":"ja","tldr":"EVM にネイティブのビットシフト命令 SHL、SHR、SAR を各 3 gas で追加し、コストの高い 2 の冪による乗算・除算の代用手段を置き換えた。","tags":["evm","opcodes","core","constantinople","gas"],"related":[1013,1014],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ja/eip-145/","markdown":"## 何を解決するのか\n\n元々の EVM には AND、OR、XOR、NOT がありましたが、ビットをシフトする手段はありませんでした。複数の値を 1 つの 256 ビットワードに詰め込むコントラクトや、データをバイト単位でデコードするコントラクトは、算術でシフトを模倣する必要がありました。左シフトには `x * 2**n`、右シフトには `x / 2**n` を使います。仕様ではこの代用手段のコストを約 35 gas としており、実行するノードの負荷も増えていました。\n\nEIP-145 は、最も安い gas 区分で 3 つの本物のシフト命令を追加します。\n\n## 仕組み\n\n| Opcode | 名前 | 結果 | 備考 |\n| --- | --- | --- | --- |\n| `0x1b` | `SHL` | `(value * 2^shift) mod 2^256` | 論理左シフト |\n| `0x1c` | `SHR` | `floor(value / 2^shift)` | 論理右シフト、ゼロ埋め |\n| `0x1d` | `SAR` | `floor(value / 2^shift)` | 算術右シフト。`value` は符号付きで、符号は保持される |\n\nいずれも 2 つのワードを pop します。最初が**シフト量**、次が**値**です。ほとんどの算術 opcode とは逆の順序です。スタック上にすでにある値を、シフト量を push するだけでシフトできるようにするためにこうなりました。\n\nエッジケース:\n\n- 256 以上のシフトは、`SHL` と `SHR` では `0` になります。`SAR` では、値が非負なら `0`、負なら `-1`（全ビット 1）になります。\n- `SAR` は符号付き除算とは異なります。`SDIV(-1, 2) == 0` ですが、`SAR(-1, 1) == -1` です。`SAR` は負の無限大方向に丸めるためです。\n\n3 つとも 3 gas（`verylow` 区分）です。この opcode は Constantinople アップグレード（[EIP-1013](/eip-1013/)）で有効になりました。\n\n## サンプルコード\n\n生の EVM で、`1` を `0xff` ビット左シフトする例:\n\n```text\nPUSH32 0x0000...0001   // value\nPUSH1  0xff            // shift amount (top of stack)\nSHL                    // -\u003e 0x8000...0000\n```\n\nSolidity では、Constantinople 以降を対象にすると `\u003c\u003c` と `\u003e\u003e` がこれらの opcode にコンパイルされます。\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\ncontract Packing {\n    // Pack two uint128 values into one storage word\n    function pack(uint128 hi, uint128 lo) external pure returns (uint256) {\n        return (uint256(hi) \u003c\u003c 128) | lo;          // SHL\n    }\n\n    function unpackHi(uint256 word) external pure returns (uint128) {\n        return uint128(word \u003e\u003e 128);               // SHR\n    }\n\n    function signedHalf(int256 x) external pure returns (int256) {\n        return x \u003e\u003e 1;                              // SAR, rounds toward -infinity\n    }\n}\n```\n\n## 知っておくべきこと\n\n- フォーク前にデプロイされたバイトコードは影響を受けません。Constantinople 以前は、これらのバイト値は単なる無効な opcode でした。\n- Constantinople 以前の EVM バージョンを対象にコンパイルすると、コンパイラは `MUL`/`DIV` と `EXP` にフォールバックします。そのため、安価な opcode を使えるかどうかはターゲット設定に依存します。\n- Solidity では、符号付き整数に対する `\u003e\u003e` は負の無限大方向に丸められ、`SAR` と一致します。負数で `/ 2` と同じ挙動になると思い込まないでください。\n"},"ko":{"lang":"ko","tldr":"EVM에 네이티브 비트 시프트 옵코드 SHL, SHR, SAR를 각각 3 gas로 추가해, 2의 거듭제곱으로 곱하고 나누던 비싼 우회 방식을 대체했다.","tags":["evm","opcodes","core","constantinople","gas"],"related":[1013,1014],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ko/eip-145/","markdown":"## 어떤 문제를 해결하나요?\n\n초기 EVM에는 AND, OR, XOR, NOT은 있었지만 비트를 시프트하는 방법은 없었습니다. 여러 값을 하나의 256비트 워드에 담거나 데이터를 바이트 단위로 디코딩하는 컨트랙트는 산술 연산으로 시프트를 흉내 내야 했습니다. 왼쪽 시프트는 `x * 2**n`, 오른쪽 시프트는 `x / 2**n`을 썼습니다. 명세는 이 우회 방식의 비용을 약 35 gas로 보며, 이를 실행하는 노드의 작업량도 늘어났습니다.\n\nEIP-145는 가장 저렴한 gas 구간에 진짜 시프트 명령어 세 개를 추가합니다.\n\n## 어떻게 동작하나요?\n\n| 옵코드 | 이름 | 결과 | 비고 |\n| --- | --- | --- | --- |\n| `0x1b` | `SHL` | `(value * 2^shift) mod 2^256` | 논리 왼쪽 시프트 |\n| `0x1c` | `SHR` | `floor(value / 2^shift)` | 논리 오른쪽 시프트, 0으로 채움 |\n| `0x1d` | `SAR` | `floor(value / 2^shift)` | 산술 오른쪽 시프트. `value`는 부호 있는 값이며 부호가 보존됨 |\n\n각 명령은 워드 두 개를 pop합니다. 먼저 **시프트 양**, 그다음 **값**입니다. 대부분의 산술 옵코드와는 순서가 반대입니다. 스택에 이미 있는 값을 시프트 양만 push해서 시프트할 수 있도록 이렇게 정했습니다.\n\n엣지 케이스:\n\n- 시프트가 256 이상이면 `SHL`과 `SHR`은 `0`을 반환합니다. `SAR`는 음이 아닌 값이면 `0`, 음수이면 `-1`(모든 비트가 1)을 반환합니다.\n- `SAR`는 부호 있는 나눗셈과 다릅니다. `SDIV(-1, 2) == 0`이지만 `SAR(-1, 1) == -1`입니다. `SAR`는 음의 무한대 방향으로 반올림하기 때문입니다.\n\n세 명령 모두 3 gas(`verylow` 구간)입니다. 이 옵코드들은 Constantinople 업그레이드([EIP-1013](/eip-1013/))에서 활성화되었습니다.\n\n## 샘플 코드\n\n순수 EVM에서 `1`을 `0xff` 비트만큼 왼쪽으로 시프트하는 예:\n\n```text\nPUSH32 0x0000...0001   // value\nPUSH1  0xff            // shift amount (top of stack)\nSHL                    // -\u003e 0x8000...0000\n```\n\nSolidity에서는 Constantinople 이상을 대상으로 하면 `\u003c\u003c`와 `\u003e\u003e`가 이 옵코드로 컴파일됩니다.\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\ncontract Packing {\n    // Pack two uint128 values into one storage word\n    function pack(uint128 hi, uint128 lo) external pure returns (uint256) {\n        return (uint256(hi) \u003c\u003c 128) | lo;          // SHL\n    }\n\n    function unpackHi(uint256 word) external pure returns (uint128) {\n        return uint128(word \u003e\u003e 128);               // SHR\n    }\n\n    function signedHalf(int256 x) external pure returns (int256) {\n        return x \u003e\u003e 1;                              // SAR, rounds toward -infinity\n    }\n}\n```\n\n## 알아둘 점\n\n- 포크 이전에 배포된 바이트코드는 영향을 받지 않습니다. Constantinople 이전에는 이 바이트 값들이 그저 유효하지 않은 옵코드였습니다.\n- Constantinople 이전 EVM 버전을 대상으로 컴파일하면 컴파일러는 `MUL`/`DIV`와 `EXP`로 대체합니다. 따라서 더 저렴한 옵코드를 쓸 수 있는지는 타깃 설정에 달려 있습니다.\n- Solidity에서 부호 있는 정수에 대한 `\u003e\u003e`는 음의 무한대 방향으로 반올림되어 `SAR`와 일치합니다. 음수에서 `/ 2`처럼 동작한다고 가정하지 마세요.\n"},"zh":{"lang":"zh","tldr":"为 EVM 原生添加 SHL、SHR 和 SAR 位移操作码，每个仅需 3 gas，取代了代价高昂的\"乘以或除以 2 的幂\"的变通写法。","tags":["evm","opcodes","core","constantinople","gas"],"related":[1013,1014],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/zh/eip-145/","markdown":"## 它解决什么问题？\n\n最初的 EVM 有 AND、OR、XOR 和 NOT，却没有移位的方法。把多个值打包进一个 256 位字，或逐字节解码数据的合约，只能用算术来模拟移位：左移用 `x * 2**n`，右移用 `x / 2**n`。规范估计这种变通写法的成本约为 35 gas，同时也给运行它的节点增加了更多工作。\n\nEIP-145 在最便宜的 gas 档位上添加了三条真正的移位指令。\n\n## 它如何运作\n\n| 操作码 | 名称 | 结果 | 说明 |\n| --- | --- | --- | --- |\n| `0x1b` | `SHL` | `(value * 2^shift) mod 2^256` | 逻辑左移 |\n| `0x1c` | `SHR` | `floor(value / 2^shift)` | 逻辑右移，补零 |\n| `0x1d` | `SAR` | `floor(value / 2^shift)` | 算术右移，`value` 为有符号数，保留符号 |\n\n每条指令弹出两个字：先是**移位量**，再是**值**。这与大多数算术操作码的顺序相反。这样设计是为了让栈上已有的值只需压入移位量就能被移位。\n\n边界情况：\n\n- 移位量为 256 或更大时，`SHL` 和 `SHR` 得到 `0`。对于 `SAR`，非负值得到 `0`，负值得到 `-1`（全为 1）。\n- `SAR` 与有符号除法不同：`SDIV(-1, 2) == 0`，但 `SAR(-1, 1) == -1`，因为 `SAR` 向负无穷方向取整。\n\n三者都花费 3 gas（`verylow` 档）。这些操作码随 Constantinople 升级（[EIP-1013](/eip-1013/)）上线。\n\n## 示例代码\n\n原始 EVM，将 `1` 左移 `0xff` 位：\n\n```text\nPUSH32 0x0000...0001   // value\nPUSH1  0xff            // shift amount (top of stack)\nSHL                    // -\u003e 0x8000...0000\n```\n\n在 Solidity 中，以 Constantinople 或更高版本为目标时，`\u003c\u003c` 和 `\u003e\u003e` 会编译为这些操作码：\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\ncontract Packing {\n    // Pack two uint128 values into one storage word\n    function pack(uint128 hi, uint128 lo) external pure returns (uint256) {\n        return (uint256(hi) \u003c\u003c 128) | lo;          // SHL\n    }\n\n    function unpackHi(uint256 word) external pure returns (uint128) {\n        return uint128(word \u003e\u003e 128);               // SHR\n    }\n\n    function signedHalf(int256 x) external pure returns (int256) {\n        return x \u003e\u003e 1;                              // SAR, rounds toward -infinity\n    }\n}\n```\n\n## 需要注意\n\n- 在分叉之前部署的字节码不受影响。在 Constantinople 之前，这些字节值只是无效的操作码。\n- 针对 Constantinople 之前的 EVM 版本编译时，编译器会回退到 `MUL`/`DIV` 加 `EXP`，因此能否使用更便宜的操作码取决于你的目标设置。\n- 在 Solidity 中，对有符号整数使用 `\u003e\u003e` 会向负无穷方向取整，与 `SAR` 一致。不要假定它对负数的行为与 `/ 2` 相同。\n"}},"requiredBy":[1013]}
