【发布时间】: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
}
- 为什么 BitArray 不能复制到无符号整数?
- 为什么在 32 位变量中 i = 31 时 '1
(对不起,重复的问题,我尝试在另一篇文章中发表评论,但我需要 50 声望) Converting a BitArray in to UInt32 C#
【问题讨论】:
-
试试
1U << i... -
1U 工作了,谢谢 pm100
-
你试过上面那个链接了吗?
-
用于在各种类型之间复制字节,有
Marshal.Copy()。在您可以使用之前有几个步骤开销,我需要查找(因此没有示例)。也许有人可以用这种方法写一个答案。
标签: c# bit-manipulation