[英]How can I cast negative double to ulong in C#?
I found a code snippet in C++ that is uint x=(uint)k * 100;
我在C ++中找到了一个uint x=(uint)k * 100;
的代码片段uint x=(uint)k * 100;
which k is a float either positive or negative. 其中k为正数或负数的浮点数。 And I must implement this code in C#. 而且我必须在C#中实现此代码。 I write this code as ulong x = Convert.ToUInt64(k * 100)
whick k is a positive or negative double in this case. 我将此代码编写为ulong x = Convert.ToUInt64(k * 100)
在这种情况下,k是正或负双精度。 So when k is positive code is working but if k is negative it gives error. 因此,当k为正数时,代码有效,但如果k为负,则产生错误。 However I am completely sure the C++ one is correct. 但是我完全可以肯定C ++是正确的。 How can I do that in C#? 如何在C#中做到这一点?
uint
or ulong
are unsigned . uint
或ulong
未签名 。 That means that they can take values starting from 0. They cannot take negative values. 这意味着它们可以采用从0开始的值。它们不能采用负值。 So when you write Convert.ToUInt64(negative_double)
it gives the following execption: 因此,当您编写Convert.ToUInt64(negative_double)
它将执行以下操作:
An unhandled exception of type 'System.OverflowException' occurred in mscorlib.dll Additional information: Arithmetic operation resulted in an overflow. mscorlib.dll中发生了'System.OverflowException'类型的未处理异常。其他信息:算术运算导致溢出。
If you still want to perform this assignment you can do same cast you do in c++
如果仍要执行此分配,则可以执行与c++
ulong x = (ulong)k * 100;
I don't know, I expect exactly what C++ solution will be return. 我不知道,我确切地期望返回什么C ++解决方案。
It will give you the same c++
result. 它将为您提供相同的c++
结果。
由于将负值转换为无符号的UInt64是错误的,因此您必须转换为有符号的Int64,然后将其转换为UInt64,您需要获得与C ++相同的结果;
var result = (UInt64)Convert.ToInt64 (k * 100);
You cannot directly convert from a double to an unsigned long, you first have to convert to a long. 您不能直接将双精度型转换为无符号长型,而首先必须转换为长型。 So try this: 所以试试这个:
ulong x = (ulong)(long)k * 100;
https://msdn.microsoft.com/en-us/library/d3d6fhea%28v=vs.120%29.aspx https://msdn.microsoft.com/zh-CN/library/d3d6fhea%28v=vs.120%29.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.