简体   繁体   中英

What is the best data type to store the result int*long in c++

What is the best configurable datatype to assign the result of int* unsigned long

For example:

int RValue1 = 4096;
unsigned long RValue2 = 1048576;

I want to store result of RValue2*RValue1 in a variabl.

I tried the following:

int RValue1 = 4096;
unsigned long RValue2 = 1048576;
long long result1 = RValue2*RValue1; //resulted 0
int64_t result2 = RValue2*RValue1;// resulted 0

Thanks in advance

Int64 is fine. You're getting 0 because your code first calculates the 32 bit product (which is 0) then stores it in int64 variable. Try this way:

int64_t result3 = (int64_t)(RValue2)*RValue1;
int RValue1 = 4096;                 // 0x1000 
unsigned long RValue2 = 1048576;    // 0x10`0000
long long result1 = RValue2*RValue1;// 0x1`0000`0000

With the above the multiplication is being done using unsigned long math, even though the result is stored in a long long . The result overflowed unsigned long 32-bit math so it "wrapped around" to 0. Had unsigned long been 64-bit, no problem would have been noted.

With mixed integer types, I recommend instead of casting, as it can sometimes narrow the type used in the computation, multiply by 1 of the target type to insure the calculation is done with at least as wide as the target's type.

long long result1 = 1LL*RValue2*RValue1;

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