2011-10-28 21 views
1

字节数组,我知道我可以使用bitconverter.GetBytes从一个整数获取字节。 然而,我需要一个阵列,其中的内容可以用于排序顺序进行比较。最快的方式排序,从符号整数

例如

var plusOne = BitConverter.GetBytes(1); 
yields bytes: 0,0,0,1 

var plusOne = BitConverter.GetBytes(2); 
yields bytes: 0,0,0,2 

到目前为止好:

但:

var minusOne = BitConverter.GetBytes(-1); 
yields bytes: 255,255,255,255 

任何异常。 但是比较minusOne字节数组和plusOne字节数组会发现minusOne字节数组大于plusOne(255> 0)

是否有任何奇妙的方式来移位,异或等,以便Int.Min会给0,0,0,0和int.Max会给255255255255?

很抱歉的混乱:)

回答

2

只需添加int.MaxValue + 1到铸造到UINT的电流值以保持像范围:

var result = BitConverter.GetBytes((uint)((long)input - int.MinValue)); 
+0

我想出了这个解决方案'unchecked((UINT)( int.MinValue ^(1 << 31)))犯规需要翻倒成一个更大的数据类型有.. –