Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to combine two uints into a ulong in c#

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.

like image 361
Jason Coyne Avatar asked Jul 30 '09 21:07

Jason Coyne


4 Answers

ulong mixed = (ulong)high << 32 | low;

The cast is very important. If you omit the cast, considering the fact that high is of type uint (which is 32 bits), you'll be shifting a 32 bit value 32 bits to the left. Shift operators on 32 bit variables will use shift stuff by right-hand-side mod 32. Effectively, shifting a uint 32 bits to the left is a no-op. Casting to ulong prevents this.

Verifying this fact is easy:

uint test = 1u;
Console.WriteLine(test << 32); // prints 1
Console.WriteLine((ulong)test << 32); // prints (ulong)uint.MaxValue + 1
like image 158
mmx Avatar answered Oct 05 '22 15:10

mmx


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.

like image 22
Adam Robinson Avatar answered Oct 05 '22 16:10

Adam Robinson


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

ulong output = highInt;
output = output << 32;
output += lowInt;
like image 42
Aric TenEyck Avatar answered Oct 05 '22 15:10

Aric TenEyck


Encoding:

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

Decoding:

uint lo = (uint)(mixed & uint.MaxValue);
uint hi = (uint)(mixed >> 32);
like image 25
Paul van Brenk Avatar answered Oct 05 '22 17:10

Paul van Brenk