加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 小端和大端分配

发布时间:2020-12-16 09:56:19 所属栏目:百科 来源:网络整理
导读:我有以下代码 int i = 321;char ch = i;printf("%d",ch); 二进制i是00000000 00000000 00000001 01000001,输出为65. 从上面的代码中,我理解由于char只占用1个字节的内存,所以i的前3个字节被删除,最后一个字节被分配给ch.因此结果. 我的机器是小端的.结果是基
我有以下代码

int i = 321;
char ch = i;
printf("%d",ch);

二进制i是00000000 00000000 00000001 01000001,输出为65.
从上面的代码中,我理解由于char只占用1个字节的内存,所以i的前3个字节被删除,最后一个字节被分配给ch.因此结果.

我的机器是小端的.结果是基于底层机器的字节顺序吗?请澄清.

解决方法

引用C11,6.3.1.3:

1 When a value with integer type is converted to another integer type
other than _Bool,if the value can be represented by the new type,it
is unchanged.

2 Otherwise,if the new type is unsigned,the value is
converted by repeatedly adding or subtracting one more than the
maximum value that can be represented in the new type until the value
is in the range of the new type.

3 Otherwise,the new type is signed and the value cannot be
represented in it; either the result is implementation-defined or an
implementation-defined signal is raised.

标准仅涉及价值观.所以如果char是无符号的:321-256 = 65.如果char已签名,则行为是实现定义的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读