转换未知盒装简单的值类型(CHAR,INT,ULONG等)UINT64 [英] Convert unknown boxed simple value types (char, int, ulong, etc.) to UInt64

查看:141
本文介绍了转换未知盒装简单的值类型(CHAR,INT,ULONG等)UINT64的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

拓展上乔恩斯基特的回答这前一题。飞碟双向没有解决的时候负值和补值进入图片时出现的故障。



在短,我想转换任何简单类型(未知举行盒装对象)以 System.UInt64形式这样我就可以与底层的二进制表示工作。



我为什么要这么做?见底部的解释。



下面的例子显示了在哪些情况下 Convert.ToInt64(对象) Convert.ToUInt64(对象)双双突破(发生OverflowException )。



有只有两个原因的 OverflowExceptions 如下:




  1. -10UL 转换为的Int64时导致异常因为负值强制转换为 0xfffffffffffffff6 (在unchecked上下文中),这比 Int64.MaxValue 的正数。 我想这转换为 -10L


  2. 当转换为 UINT64 ,符号类型拿着负值导致错误,因为 -10 例外小于 UINT64。 MINVALUE 我希望这些转换为自己的真实补值(即 0xffffffffffffffff6 )。无符号类型不真正保持负值 -10 ,因为它被转换为在unchecked上下文补;因此,也不例外无符号类型的发生。




杂牌的解决方案似乎是转化为的Int64 后跟一个未经检查的强制转换为 UINT64 。因为只有一个实例引起了的Int64 直接转换为 UINT64 时,与8故障异常这中间投会更容易些。



注:本示例使用只为迫使负值成无符号类型的目的,未经检查背景拳击(产生了积极的补等效值)中。这选中上下文不是手头的问题的一部分。



<预类=郎-CS prettyprint-覆盖> 使用系统;

枚举DumbEnum {负= -10,积极= 10};

类测试
{
静态无效的主要()
{
选中
{
检查((为sbyte)10) ;
检查((字节),10);
检查((短)10);
检查((USHORT)10);
检查((INT)10);
检查((UINT)10);
检查((长)10);
检查((ULONG)10);
检查((char)的'\\\ ');
检查((浮点)10.1);
检查((双)10.1);
检查((布尔)真);
检查((十进制),10);
检查((DumbEnum)DumbEnum.Positive);

检查((为sbyte)-10);
检查((字节)-10);
检查((短)-10);
检查((USHORT)-10);
检查((INT)-10);
检查((UINT)-10);
检查((长)-10);
//检查((ULONG)-10); //发生OverflowException
检查((浮点)-10);
检查((双)-10);
检查((布尔)FALSE);
检查((十进制)-10);
检查((DumbEnum)DumbEnum.Negative);

CheckU((为sbyte)10);
CheckU((字节)10);
CheckU((短)10);
CheckU((USHORT)10);
CheckU((int)的10);
CheckU((UINT)10);
CheckU((长)10);
CheckU((ULONG)10);
CheckU((char)的'\\\ ');
CheckU((浮点)10.1);
CheckU((双)10.1);
CheckU((布尔)真);
CheckU((十进制),10);
CheckU((DumbEnum)DumbEnum.Positive);

// CheckU((为sbyte)-10); //发生OverflowException
CheckU((字节)-10);
// CheckU((短)-10); //发生OverflowException
CheckU((USHORT)-10);
// CheckU((INT)-10); //发生OverflowException
CheckU((UINT)-10);
// CheckU((长)-10); //发生OverflowException
CheckU((ULONG)-10);
//CheckU((float)-10.1); //发生OverflowException
//CheckU((double)-10.1); //发生OverflowException
CheckU((布尔)FALSE);
// CheckU((十进制)-10); //发生OverflowException
//CheckU((DumbEnum)DumbEnum.Negative); //发生OverflowException
}
}

静态无效的检查(对象o)
{
Console.WriteLine(类型{0}转换为Int64的: {1},
o.GetType()名称,Convert.ToInt64(O));
}

静态无效CheckU(对象o)
{
Console.WriteLine(类型{0}转换为UINT64:{1},$ B $ ; b o.GetType()名称,Convert.ToUInt64(O));
}
}



为什么?



为什么我希望能够将所有这些值类型转换,并从 UINT64 ?因为我写了一个类库,转换结构或类打包成一个单一的 UINT64 值位字段。



例如:考虑在每一个IP报文头​​部,它是由一个二进制数位域的的DiffServ 字段:





使用我的类库,我可以创建一个结构来表示DiffServ字段。我创建了一个 BitFieldAttribute 这表明该位属于其中的二进制表示:

 结构的DiffServ:IBitField 
{
[位域(3,0)]
公共PrecedenceLevel优先;

[位域(1,3)]
公共BOOL延迟;

[位域(1,4)]
公共BOOL吞吐量;

[位域(1,5)]
公共BOOL可靠性;

[位域(1,6)]
公共BOOL MonetaryCost;
}

枚举PrecedenceLevel
{
常规,优先级,即时,闪光灯,FlashOverride,Crit​​icEcp,
InternetworkControl,NetworkControl
}

我的类库,可以那么这个结构的实例转换和从它的正确的二进制表示:

  //创建一个任意DiffServe实例。 
区分服务DS =新的DiffServ();
ds.Precedence = PrecedenceLevel.Immediate;
ds.Throughput = TRUE;
ds.Reliability = TRUE;

//结构转换价值。
长dsValue = ds.Pack();

//创建一个从价值结构。
DiffServ的DS2 =拆包<&DiffServ的GT;(0x66);

要做到这一点,我的类库查找字段/属性饰以 BitFieldAttribute 。获取和设置成员检索包含盒装值类型(整型,布尔,枚举等)。因此,我需要拆箱的值类型,将其转换为它的裸机二进制表示,这样的位可以被提取出来并包装物成 UINT64 值。


解决方案

我要我的后作为饲料为群众最好的解决方案。



这些转换消除所有的异常(除了非常大的浮动,双,小数对象o 时>值):

 长L = o为ULONG? (长)(ULONG)O:Convert.ToInt64(O)); 
ULONG U = 0是ULONG? (ULONG)O:(ULONG)Convert.ToInt64(O));



本的任何改进都会受到欢迎。


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:

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.

解决方案

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.

这篇关于转换未知盒装简单的值类型(CHAR,INT,ULONG等)UINT64的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆