views:

253

answers:

4

What is the best way to combine two uints into a ulong in c#, setting the high/low uints.

I know bitshifting can do it, but I don't know the syntax, or there maybe other APIs to help like BitConverter, but I don't see a method that does what I want.

+2  A: 
ulong output = (ulong)highUInt << 32 + lowUInt

The << and >> operators bitshift to the left (higher) and right (lower), respectively. highUInt << 32 is functionally the same as highUInt * Math.Pow(2, 32), but may be faster and is (IMO) simpler syntax.

Adam Robinson
It's wrong. `highInt << 32 == highInt` if `highInt` is a `uint`.
Mehrdad Afshari
Thanks, added the cast.
Adam Robinson
+12  A: 
Mehrdad Afshari
Just out of curiosity, why is the cast needed?
LiraNuna
If high is just an int, then high<<32 will be all zeros, because you just shifted all of the ones completely out of the variable. You need it to be a 64-bit integer *before* you start shifting it.
Aric TenEyck
Aric: "you just shifted all of the ones completely out of the variable" this is not completely true. Read my updated answer.
Mehrdad Afshari
+1  A: 

You have to convert the highInt to a ulong before you bitshift:

ulong output = highInt;
output = output << 32;
output += lowInt;
Aric TenEyck
A: 

Encoding:

ulong mixed = (ulong)hi << 32 | lo;

Decoding:

uint lo = (uint)(mixed & uint.MaxValue);
uint hi = (uint)(mixed >> 32);
pb