Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7755559
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T12:35:59+00:00 2026-06-01T12:35:59+00:00

Expanding on Jon Skeet’s answer to This Previous Question . Skeet doesn’t address the

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-01T12:36:00+00:00Added an answer on June 1, 2026 at 12:36 pm

    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));
    

    Any improvements to this will be welcomed.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Expanding on this question , For items that trigger dialogs and menus (i.e. non
Background Expanding upon this question. I have a collection of points (in a three
I am expanding forms that are created with Zend_Dojo , for this i have
This question is expanding on another I had gotten help with via Stackoverflow (
Expanding this question on how I learnt to pass from problem description to code
Expanding on this question , what is the best way to develop against both
I'm expanding further on this question . I currently have an asp.net hyperlink for
Expanding on this question , it looks like I did not provide enough detail.
Considering that the family of iDevices is expanding, I guess this is a problem
Expanding on my previous question here , I want to know if is possible

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.