C# - 从两个Int32中创建一个Int64

Dar*_*ine 10 c#

在c#中是否有一个函数需要两个32位整数(int)并返回一个64位一(长)?

听起来应该有一个简单的方法来做到这一点,但我找不到解决方案.

Jar*_*Par 20

请尝试以下方法

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;
}
Run Code Online (Sandbox Code Playgroud)

  • 为了安全起见,我建议使用uints和ulongs ...否则无法获得正确的数据XD.特别是如果权利是负数; 它将签到延伸至11111 ...... 111 [右] (8认同)

Jak*_*rew 12

为了清楚起见......虽然接受的答案看似正常.所有呈现的衬垫似乎都不会产生准确的结果.

这是一个有效的衬里:

long correct = (long)left << 32 | (long)(uint)right;
Run Code Online (Sandbox Code Playgroud)

这是一些代码,您可以自己测试它:

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);
Run Code Online (Sandbox Code Playgroud)

  • 第二种类型转换在技术上是多余的。你可以通过写`(long)left &lt;&lt; 32 |来缩短它。(单位)对` (2认同)