{"eip":5850,"title":"Complex Numbers stored in `bytes32` types","description":"Store real and imaginary parts of complex numbers in the least significant and most significant 16 bytes respectively of a `bytes32` type.","authors":["Paul Edge (@genkifs)"],"status":"Stagnant","type":"Standards Track","category":"ERC","created":"2022-10-29","discussionsTo":"https://ethereum-magicians.org/t/eip-5850-store-real-and-imaginary-parts-of-complex-numbers-in-the-least-significant-and-most-significant-16-bytes-respectively-of-a-bytes32-type/11532","repo":"ERCs","label":"ERC-5850","officialUrl":"https://eips.ethereum.org/EIPS/eip-5850","sourceUrl":"https://github.com/ethereum/ERCs/blob/master/ERCS/erc-5850.md","url":"https://eips.huatuo.xyz/eip-5850/","tldr":{"en":"Proposes packing a complex number into one bytes32, with the real part in the low 16 bytes and the imaginary part in the high 16 bytes, so libraries can share a common layout.","ja":"複素数を 1 つの bytes32 に詰め込み、実部を下位 16 バイト、虚部を上位 16 バイトに置くことを提案する。ライブラリが共通のレイアウトを共有できるようにするもの。","ko":"복소수를 하나의 bytes32에 담되, 실수부는 하위 16바이트, 허수부는 상위 16바이트에 두자고 제안한다. 라이브러리들이 공통 레이아웃을 공유할 수 있게 하려는 것이다.","zh":"提议把复数打包进一个 bytes32，实部放在低 16 字节，虚部放在高 16 字节，让各个库可以共用同一种布局。"},"tags":["math","solidity","encoding","library"],"explainers":{"en":{"lang":"en","tldr":"Proposes packing a complex number into one bytes32, with the real part in the low 16 bytes and the imaginary part in the high 16 bytes, so libraries can share a common layout.","tags":["math","solidity","encoding","library"],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/eip-5850/","markdown":"## What problem does it solve?\n\nComplex numbers show up in Fourier transforms, AC circuit models, signal processing and other scientific calculations. Solidity has no native complex type, so any contract or library that needs one invents its own representation: a struct, two separate variables, or some packing scheme. Different libraries then cannot pass values to each other.\n\nERC-5850 proposes one simple, shared layout: a complex number is a `bytes32`, split exactly in half.\n\n## How it works\n\n- The **real part** occupies the **least significant 16 bytes**.\n- The **imaginary part** occupies the **most significant 16 bytes**.\n- Each half holds a 128-bit value. The examples use `int128` in Cartesian form, but the ERC says any number representation (fixed point, floating point, polar or exponential forms) is acceptable as long as each component fits in 16 bytes.\n\nBecause a complex value is a plain `bytes32`, it fits in a single storage slot, can be a mapping key, and can be passed around anywhere `bytes32` is accepted. A positive real number below 2^127 maps directly onto the same `bytes32` you would get from casting the integer.\n\nThe ERC deliberately defines **only the layout**. Arithmetic (addition, multiplication, etc.) and the choice of decimal precision are left to libraries, which could be attached with `using Complex for bytes32`.\n\n## Sample code\n\nPacking and unpacking with plain bit operations (equivalent in effect to the spec's `cnNew` / `RealIm` helpers):\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\nlibrary Complex {\n    function pack(int128 re, int128 im) internal pure returns (bytes32) {\n        return bytes32(\n            (uint256(uint128(im)) \u003c\u003c 128) | uint256(uint128(re))\n        );\n    }\n\n    function unpack(bytes32 c) internal pure returns (int128 re, int128 im) {\n        re = int128(uint128(uint256(c)));        // low 16 bytes\n        im = int128(uint128(uint256(c) \u003e\u003e 128)); // high 16 bytes\n    }\n\n    // Example operation a library could provide (overflow-checked by 0.8 casts)\n    function add(bytes32 a, bytes32 b) internal pure returns (bytes32) {\n        (int128 ar, int128 ai) = unpack(a);\n        (int128 br, int128 bi) = unpack(b);\n        return pack(ar + br, ai + bi);\n    }\n}\n\ncontract Demo {\n    using Complex for bytes32;\n\n    function example() external pure returns (int128 re, int128 im) {\n        bytes32 z = Complex.pack(3, -4);      // 3 - 4i\n        bytes32 w = Complex.pack(1, 2);       // 1 + 2i\n        return z.add(w).unpack();             // (4, -2)\n    }\n}\n```\n\n## Things to know\n\n- **Status: Stagnant.** It has not progressed toward Final, and there is no sign of a widely used library built on it.\n- Do not convert the `bytes32` straight to an integer to read the real part; a non-zero imaginary part or a negative real part will give a wrong result. Always unpack.\n- If you manipulate the raw `bytes32` with assembly or unchecked math, you must handle overflow yourself, as the spec notes.\n- Precision and scaling (for example 18-decimal fixed point) are not specified, so two libraries using this layout could still disagree on what the numbers mean.\n"},"ja":{"lang":"ja","tldr":"複素数を 1 つの bytes32 に詰め込み、実部を下位 16 バイト、虚部を上位 16 バイトに置くことを提案する。ライブラリが共通のレイアウトを共有できるようにするもの。","tags":["math","solidity","encoding","library"],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ja/eip-5850/","markdown":"## 何を解決するのか\n\n複素数は、フーリエ変換、交流回路のモデル、信号処理、そのほかの科学計算に登場します。Solidity にはネイティブの複素数型がないため、複素数を必要とするコントラクトやライブラリは、構造体、2 つの別々の変数、何らかのパッキング方式など、それぞれ独自の表現を考案します。その結果、異なるライブラリ同士で値を受け渡せません。\n\nERC-5850 は、シンプルな共通レイアウトを 1 つ提案します。複素数は `bytes32` で、ちょうど半分に分割されます。\n\n## 仕組み\n\n- **実部**は**最下位の 16 バイト**を占めます。\n- **虚部**は**最上位の 16 バイト**を占めます。\n- それぞれの半分は 128 ビットの値を保持します。例では直交形式の `int128` を使っていますが、この ERC は、各成分が 16 バイトに収まる限り、どんな数値表現（固定小数点、浮動小数点、極形式、指数形式）でもかまわないとしています。\n\n複素数の値は単なる `bytes32` なので、ストレージの 1 スロットに収まり、マッピングのキーにもでき、`bytes32` が受け付けられる場所ならどこへでも渡せます。2^127 未満の正の実数は、整数をキャストして得られるのと同じ `bytes32` にそのまま対応します。\n\nこの ERC が意図的に定義するのは**レイアウトだけ**です。算術（加算、乗算など）や小数精度の選択はライブラリに委ねられており、`using Complex for bytes32` でアタッチできます。\n\n## サンプルコード\n\n単純なビット演算によるパックとアンパックです（効果は仕様の `cnNew` / `RealIm` ヘルパーと同等）:\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\nlibrary Complex {\n    function pack(int128 re, int128 im) internal pure returns (bytes32) {\n        return bytes32(\n            (uint256(uint128(im)) \u003c\u003c 128) | uint256(uint128(re))\n        );\n    }\n\n    function unpack(bytes32 c) internal pure returns (int128 re, int128 im) {\n        re = int128(uint128(uint256(c)));        // low 16 bytes\n        im = int128(uint128(uint256(c) \u003e\u003e 128)); // high 16 bytes\n    }\n\n    // Example operation a library could provide (overflow-checked by 0.8 casts)\n    function add(bytes32 a, bytes32 b) internal pure returns (bytes32) {\n        (int128 ar, int128 ai) = unpack(a);\n        (int128 br, int128 bi) = unpack(b);\n        return pack(ar + br, ai + bi);\n    }\n}\n\ncontract Demo {\n    using Complex for bytes32;\n\n    function example() external pure returns (int128 re, int128 im) {\n        bytes32 z = Complex.pack(3, -4);      // 3 - 4i\n        bytes32 w = Complex.pack(1, 2);       // 1 + 2i\n        return z.add(w).unpack();             // (4, -2)\n    }\n}\n```\n\n## 知っておくべきこと\n\n- **ステータス: Stagnant。** Final に向けて進んでおらず、これを基にした広く使われているライブラリがあるという兆候もありません。\n- 実部を読むために `bytes32` を直接整数に変換してはいけません。虚部が 0 でない場合や実部が負の場合は誤った結果になります。必ずアンパックしてください。\n- アセンブリや unchecked の演算で生の `bytes32` を操作する場合は、仕様が述べているとおり、オーバーフローを自分で処理する必要があります。\n- 精度とスケーリング（たとえば 18 桁の固定小数点）は規定されていないため、このレイアウトを使う 2 つのライブラリが、数値の意味について食い違う可能性は残ります。\n"},"ko":{"lang":"ko","tldr":"복소수를 하나의 bytes32에 담되, 실수부는 하위 16바이트, 허수부는 상위 16바이트에 두자고 제안한다. 라이브러리들이 공통 레이아웃을 공유할 수 있게 하려는 것이다.","tags":["math","solidity","encoding","library"],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ko/eip-5850/","markdown":"## 어떤 문제를 해결하나요?\n\n복소수는 푸리에 변환, 교류 회로 모델, 신호 처리, 그 밖의 과학 계산에 등장합니다. Solidity에는 네이티브 복소수 타입이 없으므로, 복소수가 필요한 컨트랙트나 라이브러리는 구조체, 별도의 변수 두 개, 어떤 패킹 방식 등 각자 자기만의 표현을 만들어 냅니다. 그러면 서로 다른 라이브러리끼리 값을 주고받을 수 없습니다.\n\nERC-5850은 간단한 공유 레이아웃 하나를 제안합니다. 복소수는 정확히 절반으로 나뉜 `bytes32`입니다.\n\n## 어떻게 동작하나요?\n\n- **실수부**는 **가장 낮은 16바이트**를 차지합니다.\n- **허수부**는 **가장 높은 16바이트**를 차지합니다.\n- 각 절반은 128비트 값을 담습니다. 예시는 직교 형식의 `int128`을 쓰지만, 이 ERC는 각 성분이 16바이트에 들어가기만 하면 어떤 숫자 표현(고정소수점, 부동소수점, 극형식, 지수 형식)이든 괜찮다고 말합니다.\n\n복소수 값은 평범한 `bytes32`이므로 스토리지 슬롯 하나에 들어가고, 매핑의 키가 될 수 있으며, `bytes32`를 받는 어디로든 전달할 수 있습니다. 2^127보다 작은 양의 실수는 그 정수를 캐스팅해서 얻는 것과 같은 `bytes32`에 그대로 대응합니다.\n\n이 ERC는 의도적으로 **레이아웃만** 정의합니다. 산술(덧셈, 곱셈 등)과 소수 정밀도의 선택은 라이브러리에 맡기며, 라이브러리는 `using Complex for bytes32`로 붙일 수 있습니다.\n\n## 샘플 코드\n\n단순한 비트 연산으로 패킹하고 언패킹하는 예시입니다(효과는 사양의 `cnNew` / `RealIm` 헬퍼와 동등합니다).\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\nlibrary Complex {\n    function pack(int128 re, int128 im) internal pure returns (bytes32) {\n        return bytes32(\n            (uint256(uint128(im)) \u003c\u003c 128) | uint256(uint128(re))\n        );\n    }\n\n    function unpack(bytes32 c) internal pure returns (int128 re, int128 im) {\n        re = int128(uint128(uint256(c)));        // low 16 bytes\n        im = int128(uint128(uint256(c) \u003e\u003e 128)); // high 16 bytes\n    }\n\n    // Example operation a library could provide (overflow-checked by 0.8 casts)\n    function add(bytes32 a, bytes32 b) internal pure returns (bytes32) {\n        (int128 ar, int128 ai) = unpack(a);\n        (int128 br, int128 bi) = unpack(b);\n        return pack(ar + br, ai + bi);\n    }\n}\n\ncontract Demo {\n    using Complex for bytes32;\n\n    function example() external pure returns (int128 re, int128 im) {\n        bytes32 z = Complex.pack(3, -4);      // 3 - 4i\n        bytes32 w = Complex.pack(1, 2);       // 1 + 2i\n        return z.add(w).unpack();             // (4, -2)\n    }\n}\n```\n\n## 알아둘 점\n\n- **상태: Stagnant.** Final로 나아가지 못했고, 이를 기반으로 만들어진 널리 쓰이는 라이브러리가 있다는 징후도 없습니다.\n- 실수부를 읽겠다고 `bytes32`를 곧바로 정수로 변환하지 마세요. 허수부가 0이 아니거나 실수부가 음수이면 잘못된 결과가 나옵니다. 항상 언패킹하세요.\n- 어셈블리나 unchecked 연산으로 원시 `bytes32`를 다룬다면, 사양이 언급하듯 오버플로를 직접 처리해야 합니다.\n- 정밀도와 스케일링(예: 소수점 18자리 고정소수점)은 명시되어 있지 않으므로, 이 레이아웃을 쓰는 두 라이브러리가 숫자의 의미에 대해 여전히 서로 다르게 해석할 수 있습니다.\n"},"zh":{"lang":"zh","tldr":"提议把复数打包进一个 bytes32，实部放在低 16 字节，虚部放在高 16 字节，让各个库可以共用同一种布局。","tags":["math","solidity","encoding","library"],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/zh/eip-5850/","markdown":"## 它解决什么问题？\n\n复数出现在傅里叶变换、交流电路模型、信号处理以及其他科学计算中。Solidity 没有原生的复数类型，因此任何需要复数的合约或库都会自创表示方式：结构体、两个独立变量，或某种打包方案。于是不同的库之间无法互相传递数值。\n\nERC-5850 提出了一种简单的共享布局：复数是一个 `bytes32`，恰好分成两半。\n\n## 它如何运作\n\n- **实部**占据**最低有效的 16 字节**。\n- **虚部**占据**最高有效的 16 字节**。\n- 每一半存放一个 128 位的值。示例使用笛卡尔形式的 `int128`，但该 ERC 表示，只要每个分量能放进 16 字节，任何数值表示（定点、浮点、极坐标或指数形式）都可以接受。\n\n由于复数值就是一个普通的 `bytes32`，它能放进单个存储槽，可以作为 mapping 的键，也可以传递到任何接受 `bytes32` 的地方。小于 2^127 的正实数直接对应于将该整数转换后得到的同一个 `bytes32`。\n\n该 ERC 有意**只定义布局**。算术运算（加法、乘法等）以及小数精度的选择留给各个库，这些库可以通过 `using Complex for bytes32` 来挂载。\n\n## 示例代码\n\n使用普通位运算进行打包和解包（效果等同于规范中的 `cnNew` / `RealIm` 辅助函数）：\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\nlibrary Complex {\n    function pack(int128 re, int128 im) internal pure returns (bytes32) {\n        return bytes32(\n            (uint256(uint128(im)) \u003c\u003c 128) | uint256(uint128(re))\n        );\n    }\n\n    function unpack(bytes32 c) internal pure returns (int128 re, int128 im) {\n        re = int128(uint128(uint256(c)));        // low 16 bytes\n        im = int128(uint128(uint256(c) \u003e\u003e 128)); // high 16 bytes\n    }\n\n    // Example operation a library could provide (overflow-checked by 0.8 casts)\n    function add(bytes32 a, bytes32 b) internal pure returns (bytes32) {\n        (int128 ar, int128 ai) = unpack(a);\n        (int128 br, int128 bi) = unpack(b);\n        return pack(ar + br, ai + bi);\n    }\n}\n\ncontract Demo {\n    using Complex for bytes32;\n\n    function example() external pure returns (int128 re, int128 im) {\n        bytes32 z = Complex.pack(3, -4);      // 3 - 4i\n        bytes32 w = Complex.pack(1, 2);       // 1 + 2i\n        return z.add(w).unpack();             // (4, -2)\n    }\n}\n```\n\n## 需要注意\n\n- **状态：Stagnant。** 它没有朝 Final 推进，也没有迹象表明有基于它构建的、被广泛使用的库。\n- 不要为了读取实部而把 `bytes32` 直接转换为整数；虚部非零或实部为负都会得到错误结果。请始终先解包。\n- 如果你用汇编或 unchecked 算术操作原始的 `bytes32`，就必须自行处理溢出，正如规范所指出的。\n- 精度和缩放（例如 18 位小数的定点数）没有被规定，因此两个使用该布局的库仍可能对数值的含义产生分歧。\n"}}}
