Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
32 ビットの符号なし数値を 32 ビットの符号付き数値に追加するときに、次のチェックが必要です。
これを実装する最もクリーンで最適な方法は何ですか?
両方を符号付き 64 ビット型に変換し、加算を実行してから、チェックを実行することをお勧めします ( min/maxマクロ/関数を使用する可能性があります)。
min
max
uint32_t add_sat(uint32_t a, int32_t b) { if (b < 0 && a < -(uint32_t)b) return 0; if (b > 0 && a + b < a) return UINT32_MAX; return a + b; }