C# - Making one Int64 from two Int32s

Try the following

public long MakeLong(int left, int right) {
  //implicit conversion of left to a long
  long res = left;

  //shift the bits creating an empty space on the right
  // ex: 0x0000CFFF becomes 0xCFFF0000
  res = (res << 32);

  //combine the bits on the right with the previous value
  // ex: 0xCFFF0000 | 0x0000ABCD becomes 0xCFFFABCD
  res = res | (long)(uint)right; //uint first to prevent loss of signed bit

  //return the combined result
  return res;
}

Just for clarity... While the accepted answer does appear to work correctly. All of the one liners presented do not appear to produce accurate results.

Here is a one liner that does work:

long correct = (long)left << 32 | (long)(uint)right;

Here is some code so you can test it for yourself:

long original = 1979205471486323557L;
int left = (int)(original >> 32);
int right = (int)(original & 0xffffffffL);

long correct = (long)left << 32 | (long)(uint)right;

long incorrect1 = (long)(((long)left << 32) | (long)right);
long incorrect2 = ((Int64)left << 32 | right);
long incorrect3 = (long)(left * uint.MaxValue) + right;
long incorrect4 = (long)(left * 0x100000000) + right;

Console.WriteLine(original == correct);
Console.WriteLine(original == incorrect1);
Console.WriteLine(original == incorrect2);
Console.WriteLine(original == incorrect3);
Console.WriteLine(original == incorrect4);

Try

(long)(((long)i1 << 32) | (long)i2)

this shifts the first int left by 32 bits (the length of an int), then ors in the second int, so you end up with the two ints concatentated together in a long.

Tags:

C#