在C#中,int是32位的,long是64位的。所以可以通过位运算把两个int合并成一个long: long foo(int h, int l) { return (h << 32) + l; }
但是,上面这个函数是有陷阱的,陷阱在哪里呢?在MSDN里面,有详细的解释:<< Operator (C# Reference) http://msdn.microsoft.com/en-us/library/a1sway8w.aspxIf the first operand is an int or uint (32-bit quantity), the shift count is given by the low-order five bits of the second operand. That is, the actual shift count is 0 to 31 bits.If the first operand is a long or ulong (64-bit quantity), the shift count is given by the low-order six bits of the second operand. That is, the actual shift count is 0 to 63 bits. 因此,上面的函数应该修改为: public static long Merge(int high, int low) { return ((long)high << 32) + low; }
long c;
c=a;
c<<32;
c=c+b;
long foo(int h, int l)
{
return (h << 32) + l;
}
http://msdn.microsoft.com/en-us/library/a1sway8w.aspxIf the first operand is an int or uint (32-bit quantity), the shift count is given by the low-order five bits of the second operand. That is, the actual shift count is 0 to 31 bits.If the first operand is a long or ulong (64-bit quantity), the shift count is given by the low-order six bits of the second operand. That is, the actual shift count is 0 to 63 bits.
因此,上面的函数应该修改为:
public static long Merge(int high, int low)
{
return ((long)high << 32) + low;
}