简体   繁体   中英

convert uint64 to uint32

I have a uint64 variable ...but the function in which I want to pass it only accepts uint32.

I tried using static unsigned int ToUInt32(uint64 variable); reference MSDN, but it gives an error that precision lost.

Is there any way to convert uint64 to uint32 without losing any data?

不能。你不能将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. 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

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

But this WILL lose you half of your number if it's bigger than 32bits.

No. A 32 bit integer has 32 bits less than a 64 bit integer. A 64 bit integer can contain anything a 32 bit integer can, but not vice versa.

Is there any way to convert uint64 to uint32 without losing any data?

Yes, but only if you know certain characteristics of your possible uint64 values and those characteristics allow a lossless conversion.

What is most likely relevant here is knowing your values will never exceed the maximum value of a 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. To do the conversion in this case, simply cast it, such as with static_cast.

If you want to handle any arbitrary uint64 value, then this is simply impossible. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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