代码之家  ›  专栏  ›  技术社区  ›  Jason Coyne

用C语言把两个uint组合成一个ulong的最好方法是什么#

  •  9
  • Jason Coyne  · 技术社区  · 15 年前

    在C_中将两个uint组合成一个ulong的最佳方法是什么,设置高/低uint。

    我知道移位可以做到,但我不知道语法,或者可能还有其他API可以帮助像BitconVerter一样,但我看不到一种方法可以实现我想要的。

    4 回复  |  直到 14 年前
        1
  •  19
  •   Mehrdad Afshari    15 年前
    ulong mixed = (ulong)high << 32 | low;
    

    演员阵容非常重要。如果你忽略了演员表,考虑到 high 属于类型 uint (32位),您将把32位值32位移到左边。32位变量上的移位运算符将使用移位数据 right-hand-side 国防部32。有效地, 换档A 无符号整型 左侧32位 是非运算 . 铸造到 ulong 防止这种情况发生。

    验证这个事实很容易:

    uint test = 1u;
    Console.WriteLine(test << 32); // prints 1
    Console.WriteLine((ulong)test << 32); // prints (ulong)uint.MaxValue + 1
    
        2
  •  2
  •   Adam Robinson    15 年前
    ulong output = (ulong)highUInt << 32 + lowUInt
    

    这个 << >> 运算符分别向左(高)和向右(低)移位。 highUInt << 32 在功能上与 highUInt * Math.Pow(2, 32) ,但可能更快,而且(IMO)语法更简单。

        3
  •  1
  •   Aric TenEyck    15 年前

    在进行位移之前,必须将highint转换为ulong:

    ulong output = highInt;
    output = output << 32;
    output += lowInt;
    
        4
  •  1
  •   Paul van Brenk    15 年前

    编码:

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

    解码:

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