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

在没有UB的情况下将64位值截断为32位值

发布时间:2020-12-16 10:25:29 所属栏目:百科 来源:网络整理
导读:这个简单的代码片段是否具有C99标准的完全定义的行为? { uint64_t longer = 0x122223333u; uint32_t shorter = longer; assert(shorter == 0x22223333u);} 如果没有,那么实现这一点的标准兼容方法是什么(将uint64_t值的低32位放到uint32_t变量中)? 解决方
这个简单的代码片段是否具有C99标准的完全定义的行为?

{
  uint64_t longer = 0x122223333u;
  uint32_t shorter = longer;
  assert(shorter == 0x22223333u);
}

如果没有,那么实现这一点的标准兼容方法是什么(将uint64_t值的低32位放到uint32_t变量中)?

解决方法

C99标准草案说:

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.

因此,在这种情况下,64位值将通过重复从中减去0x1_0000_0000来转换,直到结果符合32位(为了可读性而添加了下划线).

在您的情况下,在一次这样的减法之后,结果是0x22223333.似乎很清楚,可以证明这与仅仅进行截断是一回事,我真的不认为实际的减法会发生.

(编辑:李大同)

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

    推荐文章
      热点阅读