将一个 long 转换为两个 int 以进行重构
我需要将一个参数作为两个 int 参数传递给 Telerik Report,因为它不能接受长参数。将 long 拆分为两个 int 并在不丢失数据的情况下重建它的最简单方法是什么?
I need to pass a parameter as two int parameters to a Telerik Report since it cannot accept Long parameters. What is the easiest way to split a long into two ints and reconstruct it without losing data?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
使用掩蔽和移位是最好的选择。根据文档,long 保证为 64 位,int 保证为 32 位,因此您可以将这些位屏蔽为两个整数,然后重新组合。
请参阅:
注意全文中按位运算的使用。这避免了在使用加法或其他使用负数或舍入误差时可能出现的数值运算时可能遇到的问题。
请注意,如果您能够使用无符号整数,则可以在上面的代码中将 int 替换为 uint (在这种情况下这总是更好的选择,因为它更清楚这些位发生了什么)。
Using masking and shifting is your best bet. long is guaranteed to be 64 bit and int 32 bit, according to the documentation, so you can mask off the bits into the two integers and then recombine.
See:
Note the use of bitwise operations throughout. This avoids the problems one might get when using addition or other numerical operations that might occur using negative numbers or rounding errors.
Note you can replace int with uint in the above code if you are able to use unsigned integers (this is always preferable in this sort of situation, as it's a lot clearer what's going on with the bits).
在 C# 中进行位操作有时会很尴尬,特别是在处理有符号值时。每当您计划进行位操作时,您都需要使用无符号值。不幸的是,它不会产生最漂亮的代码。
如果您想要一种更好的方法来执行此操作,请获取 long 的原始字节并从字节中获取相应的整数。表示形式的转换并没有太大变化。
Doing bit-manipulation in C# can be awkward at times, particularly when dealing with signed values. You need to be using unsigned values whenever you plan on doing bit-manipulation. Unfortunately it's not going to yield the nicest looking code.
If you want a nicer way to do this, get the raw bytes for the long and get the corresponding integers from the bytes. The conversion to/from representations doesn't change very much.
对于未签名的,以下内容将起作用:
For unigned the following will work:
不要使用位运算,只需使用伪联合即可。这也适用于数据类型的不同组合,而不仅仅是长整型和长整型。 2 个整数。更重要的是,当您真正只关心读取和读取时,这避免了需要关心符号、字节顺序或其他低级细节。以一致的方式写入位。
Instead of mucking with bit operations, just use a faux union. This also would work for different combinations of data types, not just long & 2 ints. More importantly, that avoids the need to be concerned about signs, endianness or other low-level details when you really only care about reading & writing bits in a consistent manner.
将其与字符串进行转换比将其与两个整数进行转换要简单得多。这是一个选择吗?
Converting it to and from a string would be much simpler than converting it two and from a pair of ints. Is this an option?