简体   繁体   English

将uint64转换为uint32

[英]convert uint64 to uint32

I have a uint64 variable ...but the function in which I want to pass it only accepts uint32. 我有一个uint64变量...但我想传递它的函数只接受uint32。

I tried using static unsigned int ToUInt32(uint64 variable); 我尝试使用static unsigned int ToUInt32(uint64 variable); reference MSDN, but it gives an error that precision lost. 引用MSDN,但它给出了精度丢失的错误。

Is there any way to convert uint64 to uint32 without losing any data? 有没有办法将uint64转换为uint32而不丢失任何数据?

不能。你不能将2加仑的水装入一加仑的容器中,而且你不能将64位数据装入32位值。

Well think about what you are trying to do. 好好想想你想要做什么。 You are taking a number which will potentially take up to 64bits and then cutting in half. 你正在拿一个可能需要64位然后减半的数字。 Of course you are going to lose data in this instance. 当然,在这种情况下你会丢失数据。

If you are sure that the number being given is not going to be larger than uint32 then you can try this 如果你确定给出的数字不会大于uint32那么你可以试试这个

uint64 largeNumber = 9876543210;
uint32 smallNumber = largeNumber & 0xFFFFFFFF;

But this WILL lose you half of your number if it's bigger than 32bits. 但如果它超过32位,这将失去你的一半数量。

No. A 32 bit integer has 32 bits less than a 64 bit integer. 不是.32位整数比64位整数小32位。 A 64 bit integer can contain anything a 32 bit integer can, but not vice versa. 64位整数可以包含32位整数的任何内容,但反之亦然。

Is there any way to convert uint64 to uint32 without losing any data? 有没有办法将uint64转换为uint32而不丢失任何数据?

Yes, but only if you know certain characteristics of your possible uint64 values and those characteristics allow a lossless conversion. 是的,但前提是您知道可能的uint64值的某些特征,并且这些特征允许无损转换。

What is most likely relevant here is knowing your values will never exceed the maximum value of a uint32. 这里最有可能的是知道你的值永远不会超过uint32的最大值。 In this case, what you actually have is a 32-bit value stored in 64 bits and the conversion simply changes how it is stored rather than changing the value. 在这种情况下,您实际拥有的是以64位存储的32位值,转换只是更改它的存储方式而不是更改值。 To do the conversion in this case, simply cast it, such as with static_cast. 要在这种情况下进行转换,只需转换它,例如使用static_cast。

If you want to handle any arbitrary uint64 value, then this is simply impossible. 如果你想处理任意uint64值,那么这根本不可能。 If it were possible, you could compress any file, including a 40 terabyte database, down to a single 32-bit value by repeated application of the conversion. 如果可能,您可以通过重复应用转换将任何文件(包括40 TB数据库)压缩到单个32位值。

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

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