[英]math operation between 2 uint32_t returning an uint64_t
I'm trying to implement an operation, a function, with an interface like this one uint64_t foo(uint32_t,uint32_t)
, so this is a simple implementation: 我正在尝试使用像这样的接口uint64_t foo(uint32_t,uint32_t)
来实现一个操作,一个函数,所以这是一个简单的实现:
#include <iostream>
#include <cstdint>
uint64_t foo(const uint32_t &a, const uint32_t &b) {
return ((reinterpret_cast<const uint64_t &>(a)) +
(reinterpret_cast<const uint64_t &>(b)));
}
int main() {
uint32_t k1 = ~0;
uint32_t k2 = 1;
std::cout << foo(k1, k2) << "\n";
return (0);
}
Now my focus is on the reinterpret_cast
and the +
operator. 现在,我的重点是reinterpret_cast
和+
运算符。
the +
operator should be fine where it is because it's being called by 2 uint64_t
; +
运算符应该是正确的,因为它由2 uint64_t
调用; so the problem is the reinterpret_cast
? 那么问题是reinterpret_cast
吗? I don't get why ... My speculation is about the chunk of memory that is near a
or b
, so the result of the reinterpret_cast
is a 50% of the original a
or b
and the other 50% is a random chunk of memory. 我不明白为什么...我的猜测是关于a
或b
附近的内存块,因此reinterpret_cast
的结果是原始a
或b
的50%,另外50%是随机的a记忆。 I this how this cast really works ? 我这个演员表如何真正起作用?
I already tried several versions of a reinterpret_cast
, even with pointers, with no luck. 我已经尝试了多个版本的reinterpret_cast
,即使使用了指针也没有运气。
reinterpret_cast
essentially tells the compiler to ignore all its type-safety and just accept what you are doing. reinterpret_cast
本质上告诉编译器忽略其所有类型安全性,仅接受您正在执行的操作。
You are saying that your reference is not a reference to a 32-bit number but to a 64-bit number. 您是说您的引用不是对32位数字的引用,而是对64位数字的引用。 That does of course mean (in 8-bits-per-byte system), 4 bytes that could potentially contain any data are read as part of your integer. 这当然意味着(在每字节8位系统中),可能包含任何数据的4个字节将作为整数的一部分被读取。 You also have a "portability" issue related to big-endian systems in particular where the more significant bytes appear first and therefore will yield a different number even if the other bytes do happen to be zero. 您还会遇到一个与“大端”系统有关的“可移植性”问题,尤其是在优先级更高的字节首先出现的情况下,即使其他字节碰巧为零,也会产生不同的数字。
Your correct way to perform this is static_cast
and not use references but "pass-by-value". 您执行此操作的正确方法是static_cast
,不要使用引用,而应使用“传递值”。
As it is, you can manage to write foo without any casting at all. 实际上,您可以编写foo而无需进行任何强制转换。
uint64_t foo( uint64_t a, uint64_t b ) { return a + b; }
and you can call it with 32-bit numbers and not worry if they overflow. 您可以使用32位数字来调用它,而不必担心它们是否溢出。 (Try it with multiplying them). (尝试乘以它们)。
You're trying too hard. 你太努力了 Pass by value and use static_cast
. 按值传递并使用static_cast
。 Also, use uint_least32_t
or uint_fast32_t
, whichever is more appropriate, rather than insisting on an exact size that may not exist. 另外,请使用uint_least32_t
或uint_fast32_t
两者中较合适的一种,而不要坚持可能不存在的确切大小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.