Kevin P. Rice
Kevin P. Rice

Reputation: 5743

Convert unknown boxed simple value types (char, int, ulong, etc.) to UInt64

Expanding on Jon Skeet's answer to This Previous Question. Skeet doesn't address the failure that occurs when negative values and two's complement values enter the picture.

In short, I want to convert any simple type (held in an unknown boxed object) to System.UInt64 so I can work with the underlying binary representation.

Why do I want to do this? See the explanation at the bottom.

The example below shows the cases where Convert.ToInt64(object) and Convert.ToUInt64(object) both break (OverflowException).

There are only two causes for the OverflowExceptions below:

  1. -10UL causes an exception when converting to Int64 because the negative value casts to 0xfffffffffffffff6 (in the unchecked context), which is a positive number larger than Int64.MaxValue. I want this to convert to -10L.

  2. When converting to UInt64, signed types holding negative values cause an exception because -10 is less than UInt64.MinValue. I want these to convert to their true two's complement value (which is 0xffffffffffffffff6). Unsigned types don't truly hold the negative value -10 because it is converted to two's complement in the unchecked context; thus, no exception occurs with unsigned types.

The kludge solution would seem to be conversion to Int64 followed by an unchecked cast to UInt64. This intermediate cast would be easier because only one instance causes an exception for Int64 versus eight failures when converting directly to UInt64.

Note: The example uses an unchecked context only for the purpose of forcing negative values into unsigned types during boxing (which creates a positive two's complement equivalent value). This unchecked context is not a part of the problem at hand.

using System;

enum DumbEnum { Negative = -10, Positive = 10 };

class Test
{
  static void Main()
  {
    unchecked
    {
      Check((sbyte)10);
      Check((byte)10);
      Check((short)10);
      Check((ushort)10);
      Check((int)10);
      Check((uint)10);
      Check((long)10);
      Check((ulong)10);
      Check((char)'\u000a');
      Check((float)10.1);
      Check((double)10.1);
      Check((bool)true);
      Check((decimal)10);
      Check((DumbEnum)DumbEnum.Positive);

      Check((sbyte)-10);
      Check((byte)-10);
      Check((short)-10);
      Check((ushort)-10);
      Check((int)-10);
      Check((uint)-10);
      Check((long)-10);
      //Check((ulong)-10);   // OverflowException
      Check((float)-10);
      Check((double)-10);
      Check((bool)false);
      Check((decimal)-10);
      Check((DumbEnum)DumbEnum.Negative);

      CheckU((sbyte)10);
      CheckU((byte)10);
      CheckU((short)10);
      CheckU((ushort)10);
      CheckU((int)10);
      CheckU((uint)10);
      CheckU((long)10);
      CheckU((ulong)10);
      CheckU((char)'\u000a');
      CheckU((float)10.1);
      CheckU((double)10.1);
      CheckU((bool)true);
      CheckU((decimal)10);
      CheckU((DumbEnum)DumbEnum.Positive);

      //CheckU((sbyte)-10);  // OverflowException
      CheckU((byte)-10);
      //CheckU((short)-10);  // OverflowException
      CheckU((ushort)-10);
      //CheckU((int)-10);    // OverflowException
      CheckU((uint)-10);
      //CheckU((long)-10);   // OverflowException
      CheckU((ulong)-10);
      //CheckU((float)-10.1);  // OverflowException
      //CheckU((double)-10.1); // OverflowException
      CheckU((bool)false);
      //CheckU((decimal)-10);  // OverflowException
      //CheckU((DumbEnum)DumbEnum.Negative); // OverflowException
    }
  }

  static void Check(object o)
  {
    Console.WriteLine("Type {0} converted to Int64: {1}",
                    o.GetType().Name, Convert.ToInt64(o));
  }

  static void CheckU(object o)
  {
    Console.WriteLine("Type {0} converted to UInt64: {1}",
                    o.GetType().Name, Convert.ToUInt64(o));
  }
}

WHY?

Why do I want to be able to convert all these value types to and from UInt64? Because I have written a class library that converts structs or classes to bit fields packed into a single UInt64 value.

Example: Consider the DiffServ field in every IP packet header, which is composed of a number of binary bit fields:

IP packet DiffServ field

Using my class library, I can create a struct to represent the DiffServ field. I created a BitFieldAttribute which indicates which bits belong where in the binary representation:

struct DiffServ : IBitField
{
    [BitField(3,0)]
    public PrecedenceLevel Precedence;

    [BitField(1,3)]
    public bool Delay;

    [BitField(1,4)]
    public bool Throughput;

    [BitField(1,5)]
    public bool Reliability;

    [BitField(1,6)]
    public bool MonetaryCost;
}

enum PrecedenceLevel
{
    Routine, Priority, Immediate, Flash, FlashOverride, CriticEcp,
    InternetworkControl, NetworkControl
}

My class library can then convert an instance of this struct to and from its proper binary representation:

// Create an arbitrary DiffServe instance.
DiffServ ds = new DiffServ();
ds.Precedence = PrecedenceLevel.Immediate;
ds.Throughput = true;
ds.Reliability = true;

// Convert struct to value.
long dsValue = ds.Pack();

// Create struct from value.
DiffServ ds2 = Unpack<DiffServ>(0x66);

To accomplish this, my class library looks for fields/properties decorated with the BitFieldAttribute. Getting and setting members retrieves an object containing the boxed value type (int, bool, enum, etc.) Therefore, I need to unbox any value type and convert it to it's bare-bones binary representation so that the bits can be extracted and packed into a UInt64 value.

Upvotes: 4

Views: 1662

Answers (1)

Kevin P. Rice
Kevin P. Rice

Reputation: 5743

I'm going to post my best solution as fodder for the masses.

These conversions eliminate all exceptions (except for very large float, double, decimal values which do not fit in 64-bit integers) when unboxing an unknown simple value type held in object o:

long l = o is ulong ? (long)(ulong)o : Convert.ToInt64(o));
ulong u = o is ulong ? (ulong)o : (ulong)Convert.ToInt64(o));

And for avoiding an extra cast in modern C# versions:

long l = o is ulong v ? (long)v : Convert.ToInt64(o));
ulong u = o is ulong v ? v : (ulong)Convert.ToInt64(o));

Any improvements to this will be welcomed.

Upvotes: 3

Related Questions