简体   繁体   中英

How can I cast negative double to ulong in C#?

I found a code snippet in C++ that is uint x=(uint)k * 100; which k is a float either positive or negative. And I must implement this code in C#. I write this code as ulong x = Convert.ToUInt64(k * 100) whick k is a positive or negative double in this case. So when k is positive code is working but if k is negative it gives error. However I am completely sure the C++ one is correct. How can I do that in C#?

uint or ulong are unsigned . That means that they can take values starting from 0. They cannot take negative values. So when you write Convert.ToUInt64(negative_double) it gives the following execption:

An unhandled exception of type 'System.OverflowException' occurred in mscorlib.dll Additional information: Arithmetic operation resulted in an overflow.

If you still want to perform this assignment you can do same cast you do in c++

ulong x = (ulong)k * 100;

I don't know, I expect exactly what C++ solution will be return.

It will give you the same c++ result.

由于将负值转换为无符号的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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM