从有符号整数获取排序顺序字节数组的最快方法

时间:2011-10-28 07:24:39

标签: c# signed bitconverter

我知道我可以使用bitconverter.GetBytes从整数中获取字节。 但是,我需要一个数组,其中可以比较排序顺序的内容。

e.g。

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)

是否有任何奇特的移位方式,xor等,以便Int.Min会给0,0,0,0和int.Max会给出255,255,255,255 ??

很抱歉这个混乱:)

1 个答案:

答案 0 :(得分:2)

只需将int.MaxValue + 1添加到转换为uint的当前值,即可保留范围,如:

var result = BitConverter.GetBytes((uint)((long)input - int.MinValue));
相关问题