I have int
variable with value 820924
when I'm trying to convert it like that:
(uint)data[structure["MICROSECONDS"].Index]
it doesn't work.
This doesn't work as well
unchecked((uint)data[structure["MICROSECONDS"].Index])
I receive Specified cast is not valid.
exception.
Data stores object
, but at run time I should try to convert to int
. I'm almost sure. I've printed object value it was 820924
, however I don't know how to print object type, but it must be int.
Code:
object value = data[structure["MICROSECONDS"].Index]; Console.WriteLine("xx MICROSECONDS type " + value.GetType()); Console.WriteLine("xx casting " + value); Console.WriteLine("xx cast ok" + (uint)value);
Result:
xx MICROSECONDS type System.Int32 xx casting 820924
Casting from int , uint , or long to a float could result in the loss of precision, but never magnitude. Casting from long to a double could result in the loss of precision, but never magnitude.
Conversions between integer types do not require casts in C++. They are standard conversions, and they are performed implicitly. In your case you could simply do unsigned int j = i; for exactly the same effect.
uint means “unsigned integer” while int means “signed integer”. Unsigned integers only contain positive numbers (or zero).
Since we use number with positive and negative integers more often than positive integers only, the type Int is the signed integers. If we want a value without a sign, then we use the type UInt . UInt creates a integer of the same bit size as the device's processor can handle.
First of all you should check the type of your value. You can do it by calling obj.GetType()
method (either in your code directly or in Immediate window).
If it is int
then you can do:
uint u = (uint) (int) obj;
Please note that it differs from your cast because it casts to int
and then converts to uint
while you were trying to cast to uint
. int
cannot be cast to uint
and that is why you get the InvalidCastException
. int
can be only converted to uint
. It is confusing that both conversion and cast operators look same in code: u = (uint) x
.
Easier thing you can do is calling a specific method from Convert
class:
uint u = Convert.ToUInt32(x);
The problem is that int
is stored as object
. Int
derives from object but uint
doesn't derive from int
so you can't cast int
stored as object
to uint
. First you have to cast it to int
and then to uint
because that cast is valid. Try it yourself:
object o = 5;//this is constant that represents int, constant for uint would be 5u uint i = (uint)o;//throws exception
But this works:
object o = 5; int i = (int)o; uint j = (uint)i;
or
object o = 5; uint i = (uint)(int)o; //No matter how this looks awkward
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With