patterncppModerate
Combining two 32-bit integers into one 64-bit integer
Viewed 0 times
bitcombiningintotwooneintegersinteger
Problem
long long combine(unsigned int high, unsigned int low) {
return ((unsigned long long) high) << 32 || low;
}- Is there a better name for the operation?
- Is the implicit cast from
unsigned long longtolong longareinterpret_cast, or what happens if theunsignednumber is too large for thesigneddata type?
Solution
You should return
I'd prefer a name such as
Also, I'd consider being more pedantic:
It's unlikely to make a difference because the code is essentially the same as yours, but it's easier to read and avoids extremely rare (but very troublesome to debug) casting issues. It may require a custom types header if your compiler doesn't support this type notation.
Also, consider making it a macro. There's little benefit to having it as a function - the operation itself will take far less time than the function call setup, call, and return, so the performance of a macro will be much higher. Further, it isn't going to take up much more program space than a function call, so there's little to gain by leaving it a real function.
unsigned long long and let the user decide what they want to do with the cast, especially if you want this to be generic.I'd prefer a name such as
u32tou64, uinttoull, or something more descriptive than combine. A lot of this will depend on your own naming standards, though.Also, I'd consider being more pedantic:
return (((uint64_t) high) << 32) | ((uint64_t) low);It's unlikely to make a difference because the code is essentially the same as yours, but it's easier to read and avoids extremely rare (but very troublesome to debug) casting issues. It may require a custom types header if your compiler doesn't support this type notation.
Also, consider making it a macro. There's little benefit to having it as a function - the operation itself will take far less time than the function call setup, call, and return, so the performance of a macro will be much higher. Further, it isn't going to take up much more program space than a function call, so there's little to gain by leaving it a real function.
Code Snippets
return (((uint64_t) high) << 32) | ((uint64_t) low);Context
StackExchange Code Review Q#2607, answer score: 10
Revisions (0)
No revisions yet.