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

发布于 2024-12-12 12:18:46 字数 560 浏览 0 评论 0原文

我知道我可以使用 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技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

春花秋月 2024-12-19 12:18:46

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

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

Simply add int.MaxValue + 1 to the current value casted to an uint to preserve the range like:

var result = BitConverter.GetBytes((uint)((long)input - int.MinValue));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文