c – 小端和大端分配

c – 小端和大端分配,第1张

概述我有以下代码 int i = 321;char ch = i;printf("%d", ch); 二进制i是00000000 00000000 00000001 01000001,输出为65. 从上面的代码中,我理解由于char只占用1个字节的内存,所以i的前3个字节被删除,最后一个字节被分配给ch.因此结果. 我的机器是小端的.结果是基于底层机器的字节顺序吗?请澄清. 引用C11,6.3.1 我有以下代码

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已签名,则行为是实现定义的.

总结

以上是内存溢出为你收集整理的c – 小端和大端分配全部内容,希望文章能够帮你解决c – 小端和大端分配所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1216483.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存