简体   繁体   English

如何以类型安全的方式分配uint32_t :: max和uint64_t的最小值?

[英]How to assign min of uint32_t::max and uint64_t in type safe manner?

I want to assign minimum of difference of two uint64_t numbers and maximum numerical limit of uint32_t in type safe manner. 我想以类型安全的方式分配两个uint64_t数字之差的最小值和uint32_t的最大数值限制。 Is there a way to do it? 有办法吗?

uint32_t max32 = std::numeric_limits<uint32_t>::max();
uint64_t a, b;

uint32_t minValue = std::min(max32, b - a);
                               ^^^^^^ (Parameter mismatch warning)

Basically. 基本上。 if the difference between a and b is greater than maximum value of uint32_t, I want to use the max value else I want to use the difference. 如果a和b之间的差异大于uint32_t的最大值,我想使用最大值,否则我想使用差异。 I need to use minValue in an API that only accepts uint32_t. 我需要在仅接受uint32_t的API中使用minValue

You can use: 您可以使用:

minValue = static_cast<uint32_t>(
               std::min(static_cast<uint64_t>(max32),
                        a < b ? b - a : a - b));

The static_cast creates a 64-bit unsigned value from max32 to match the type of the diff of a and b . static_castmax32创建一个64位无符号值,以匹配ab的diff类型。

Note that when you subtract a larger unsigned number from a smaller one, the result will wrap around - often to some very large number. 请注意,当您从较小的数字中减去较大的无符号数字时,结果将回绕-通常为一个非常大的数字。 For example, (uint8_t)2 - (uint8_t)3 will yield 255. That's why I use the ? 例如, (uint8_t)2 - (uint8_t)3将产生255。这就是为什么我使用?的原因? / : logic to work out which way around to perform the subtraction. / :找出执行减法的逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM