从ULONG复制位长期在C# [英] Copy bits from ulong to long in C#

查看:111
本文介绍了从ULONG复制位长期在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,现在看来, .NET性能计数器类型有一个恼人问题:它暴露为计数器RawValue而在Windows中的实际性能计数器的值是无符号数,不能为负数。举例来说,如果你有一个NumberOfItems64计数器的API会很乐意接受一个负值,然后静静地将其转换为一个非常大的数字。事实上,对于取值范围一半的柜台设置的唯一途径有找到正确的负价值传递!

So it appears that the .NET performance counter type has an annoying problem: it exposes long for the counter RawValue while the actual perf counter value in windows is unsigned and cannot be negative. For instance if you have a NumberOfItems64 counter The API will be perfectly happy to accept a negative value, then silently convert it to a very large number. In fact for half the value range of the counter the only way to set it there is to find the correct negative value to pass in!

我以为这里发生了什么时他们正在从以原位,把它当作一个无符号64位数字。从补的负值只是解读为反直线号码。

I assume what is happening here is that they are taking the raw bits from the long and treating it as an unsigned 64-bit number. The negative values from two's complement are just read as a straight up number for the counter.

所以我想弄清楚如何强制C#逼到下探位从 ULONG 直入,因为这是该API想要什么。但是C#是太有帮助......在这里,你可以不投或使用 Convert.ToInt64(ULONG),因为它抛出,因为该值是太大的溢出异常。我偶然发现这样的转换是这样的:

So I'm trying to figure out how to coerce C# into just dropping the bits from the ulong straight into the long, since that's what the API wants. But C# is being too helpful here... you can't cast or use Convert.ToInt64(ulong) since it throws overflow exceptions because of the value being too large. I stumbled upon this way of doing the conversion:

Convert.ToInt64(myULong.ToString(X),16)

当它从非底座10的字符串转换它假定的数量是二的补和做什么我需要它。但由于它需要分配一个对象并解析每次转换一个字符串,这个API将是关键性能是不理想的。有没有在C#中的更好的方式来做到这一点?

When it converts from a string in non-base 10 it assumes the number is in two's complement and does what I need it to. But it's not ideal because it needs to allocate an object and parse a string for every conversion and this API is going to be performance-critical. Is there a better way in C# to do this?

推荐答案

一个简单的铸像

ulong value1 = 0xFEDCBA9876543210UL;  // 18364758544493064720
long value2 = (long)value1;           // -81985529216486896
ulong value3 = (ulong)value2;         // 18364758544493064720



在保持完全值位。

preserves the bits in the value exactly.

这篇关于从ULONG复制位长期在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆