-1

I'm trying to programmatically convert a boxed int into an uint.

The code I'm using is this:

Type targetType = methodToInvoke.GetParameters()[index].ParameterType;
object operand = currentMethod.Body.Instructions[j - 1].Operand;
if (targetType.IsValueType)
{
    parameters[index] = Convert.ChangeType(operand, targetType);
}

VS tell me that targetType is of type:

{Name = "UInt32" FullName = "System.UInt32"}

Instead operand is of type:

object {int}

ChangeType throw a System.OverflowException when the value of operand is -1549600314.

  • Why is this happening, provided that the two values are 32 bit long?

  • How am I supposed to do this conversion?

2
  • 2
    Wait, are you asking why you can't convert a negative integer to an unsigned integer? Think about that for a second.
    – pquest
    May 25, 2016 at 19:04
  • Yeah, that's definitely what I'm asking. Maybe I'm missing the point with Convert.ChangeType but this is definitely possible. So, how am I supposed to do this conversion?
    – Chaplin89
    May 25, 2016 at 19:25

1 Answer 1

1

Why is this happening, provided that the two values are 32 bit long?

Because Convert.ChangeType just calls methods from the IConvertible interface, which uses value semantics.

From MSDN:

Convert.ChangeType Method (Object, Type)

Returns an object of the specified type and whose value is equivalent to the specified object.

(emphasis added)

How am I supposed to do this conversion?

It sounds like you just want a quick bitwise conversion, which can be done by just unboxing the int and casting to unit:

unchecked {
    parameters[index] = (uint)(int)operand;
}

or if you don't like unchecked operations:

parameters[index] = BitConverter.ToUInt32(BitConverter.GetBytes((int)operand), 0)
3
  • Thank you for your reply, very clear. So I guess there isn't a "general" way to do this. I mean, in my snippet operand and targetType can be of any reasonable type, this imply that with your solution I've to manage the "int" case explicitly.
    – Chaplin89
    May 25, 2016 at 20:12
  • No, there's not a "generic" BitConverter because the process depends highly on the target and destination types. Converting a byte to a uint is different that converting a long to a short, for example.
    – D Stanley
    May 25, 2016 at 20:18
  • Make sense. Thanks.
    – Chaplin89
    May 25, 2016 at 20:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.