【问题标题】:c# convert a 32bit BitArray to a UInt32c# 将 32 位 BitArray 转换为 UInt32
【发布时间】:2017-05-31 22:10:59
【问题描述】:

我正在尝试将 BitArray 中的 32 位转换为 Win7 64 位中的 32 位 c# NET4.0 应用程序中的 UInt32。

我尝试了两种技术,但都抛出异常。

当使用 CopyTo 时,它会抛出这个: System.ArrayTypeMismatchException:源数组类型无法分配给目标数组类型。

BitArray newBits = new BitArray(32);
// (modify bits...)

UInt32[] intArray = new UInt32[1];
newBits.CopyTo(intArray, 0); // < crash

当手动设置位时,当它到达第 32 位时(当 i = 31 时)会抛出这个: System.OverflowException:算术运算导致溢出。

BitArray newBits = new BitArray(32);
// (modify bits...) 

UInt32 res = 0;
for (int i = 0 ; i < newBits.Length ; i++) 
{
    //Debug("i="+i+", "+newBits.Length);
    if (newBits[i]) res |= (UInt32)(1 << i); // < crash when i reaches 31
}   
  1. 为什么 BitArray 不能复制到无符号整数?
  2. 为什么在 32 位变量中 i = 31 时 '1

(对不起,重复的问题,我尝试在另一篇文章中发表评论,但我需要 50 声望) Converting a BitArray in to UInt32 C#

【问题讨论】:

  • 试试1U &lt;&lt; i ...
  • 1U 工作了,谢谢 pm100
  • 你试过上面那个链接了吗?
  • 用于在各种类型之间复制字节,有Marshal.Copy()。在您可以使用之前有几个步骤开销,我需要查找(因此没有示例)。也许有人可以用这种方法写一个答案。

标签: c# bit-manipulation


【解决方案1】:
  1. 实施不支持将BitArray 复制到UInt32,根据documentation 这是最近(10/2016):

指定的数组必须是兼容的类型。仅支持 bool、int 和 byte 类型的数组。

  1. int 中的最高有效位是used to store the sign。要告诉编译器您希望数字文字无符号,请使用 U 后缀:1U &lt;&lt; 31

【讨论】:

    【解决方案2】:

    问题已得到解释,但为了完整起见,尚未明确说明您对此做了什么:

    您应该使用CopyTo 转换为int[],然后将您的 int 转换为 uint,如下所示(未测试)

    int[] temp = new int[1];
    bits.CopyTo(temp);
    uint asUint = unchecked((uint)temp[0]);
    

    unchecked 有点傻,但您似乎已打开“默认检查算术”复选框(否则 (uint)(1 &lt;&lt; i) 会起作用 - 没有固有问题,它只是在 @ 987654326@ 上下文)。

    或者甚至比上面更好,如果你 BitArray 很短,你可以完全避免使用它,而总是使用 uint 的位。

    【讨论】:

      猜你喜欢
      • 2016-09-06
      • 2017-10-05
      • 2012-06-27
      • 2015-10-03
      • 2015-06-06
      • 2013-12-26
      • 1970-01-01
      • 2018-02-27
      • 1970-01-01
      相关资源
      最近更新 更多