从有符号整数获取排序顺序字节数组的最快方法
我知道我可以使用 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 会给出 255,255,255,255 ??
抱歉造成混乱:)
I know I can use bitconverter.GetBytes to get the bytes from an integer.
However, I need an array where the contents can be compared for sort order.
e.g.
var plusOne = BitConverter.GetBytes(1);
yields bytes: 0,0,0,1
var plusOne = BitConverter.GetBytes(2);
yields bytes: 0,0,0,2
So far so good:
but:
var minusOne = BitConverter.GetBytes(-1);
yields bytes: 255,255,255,255
Nothing strange here.
But comparing the minusOne byte array with the plusOne bytearray would say that the minusOne byte array is greater than the plusOne (255 > 0)
Is there any fancy way to shift, xor etc, so that Int.Min would give 0,0,0,0 and int.Max would give 255,255,255,255 ??
Sorry for the confusion :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需将
int.MaxValue + 1
添加到转换为 uint 的当前值即可保留范围,例如:Simply add
int.MaxValue + 1
to the current value casted to an uint to preserve the range like: