微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c – 在将uint64_t截断为uint8_t [i]时,我应该使用位掩码吗?

如果我有一个大的int,比如uint64_t,和一个uint8_t的数组,例如:
uint64_t large = 12345678901234567890;
uint8_t small[5];

我想将uint64_t的8个最低有效位复制到uint8_t数组的元素中,使用它是否安全:

small[3] = large;

或者我应该使用位掩码:

small[3] = large & 255;

即是否有任何情况,大型int的其余部分可能以某种方式溢出到阵列的其他元素?

解决方法

这非常安全:
small[3] = large;

并且[conv.integral]中明确描述了这种转换:

If the destination type is unsigned,the resulting value is the least unsigned integer congruent to the source
integer (modulo 2n where n is the number of bits used to represent the unsigned type).

也就是说,这四个语句都保证在小[3]中以相同的值结束:

small[3] = large;
small[3] = large % 256;
small[3] = large & 255;
small[3] = static_cast<uint8_t>(large);

没有功能上的理由来做%或&或者投你自己,但是如果你想要的话,如果编译器没有为所有四个(gcc和clang do)生成相同的代码,我会感到惊讶.

一个区别是,如果您使用-Wconversion之类的东西进行编译,这会导致发出警告(这有时可能是有益的).在这种情况下,你会想要演员.

原文地址:https://www.jb51.cc/c/117922.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐