简体   繁体   English

在c#中将两个uint组合成ulong的最佳方法是什么?

[英]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. 在c#中将两个uint组合成ulong的最佳方法是什么,设置高/低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. 我知道bitshifting可以做到这一点,但我不知道语法,或者可能有其他API来帮助像BitConverter,但我没有看到一个方法做我想要的。

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. 如果你省略了强制转换,考虑到highuint类型(32位)的事实,你将把32位值32位向左移位。 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 . 移在32个变量运营商将通过使用移位东西right-hand-side模32有效地, 移位uint 32位到左侧是一个空操作 Casting to ulong prevents this. 施放到ulong可以防止这种情况发生。

Verifying this fact is easy: 验证这个事实很容易:

uint test = 1u;
Console.WriteLine(test << 32); // prints 1
Console.WriteLine((ulong)test << 32); // prints (ulong)uint.MaxValue + 1
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. highUInt << 32在功能上与highUInt * Math.Pow(2, 32) ,但可能更快并且是(IMO)更简单的语法。

You have to convert the highInt to a ulong before you bitshift: 你必须在bithift之前将highInt转换为ulong:

ulong output = highInt;
output = output << 32;
output += lowInt;

Encoding: 编码方式:

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

Decoding: 解码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM