算术溢出等于模运算吗? [英] Is arithmetic overflow equivalent to modulo operation?

查看:119
本文介绍了算术溢出等于模运算吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在C语言中执行256模运算.所以我可以简单地进行

I need to do modulo 256 arithmetic in C. So can I simply do

unsigned char i;
i++;

代替

int i;
i=(i+1)%256;

推荐答案

否.没有什么可以保证unsigned char具有八位.使用<stdint.h>中的uint8_t,您会很好的.这需要支持stdint.h的实现:任何符合C99的编译器都支持,但是较早的编译器可能不提供.

No. There is nothing that guarantees that unsigned char has eight bits. Use uint8_t from <stdint.h>, and you'll be perfectly fine. This requires an implementation which supports stdint.h: any C99 compliant compiler does, but older compilers may not provide it.

注意:无符号算术永远不会溢出,并且表现为模2 ^ n".带符号的算术溢出并具有未定义的行为.

Note: unsigned arithmetic never overflows, and behaves as "modulo 2^n". Signed arithmetic overflows with undefined behavior.

这篇关于算术溢出等于模运算吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆