【问题标题】:Convert BitArray to integer in PowerShell在 PowerShell 中将 BitArray 转换为整数
【发布时间】:2020-10-19 16:31:09
【问题描述】:

总结

我正在尝试使用 PowerShell 版本 7 将 32 位 BitArray 转换为整数。我尝试了 C# 处理它的方式,但它不起作用。

这是我的代码。

$high = [System.Collections.BitArray]::new(@(0x93e0))
$low = [System.Collections.BitArray]::new(@(0x0004))
$low += $high.LeftShift(16)

# Create an integer array with a length of 1
$result = [int[]]::new(1)

# Copy the BitArray to the integer at index 0
$low.CopyTo($result), 0)

实际结果

抛出异常。

MethodInvocationException: Exception calling "CopyTo" with "2" argument(s): "Destination array was not long enough. Check the destination index, length, and the array's lower bounds. (Parameter 'destinationArray')"

预期结果

$result 变量填充了以整数表示的BitArray 的值。

【问题讨论】:

  • $low += $high.LeftShift(16) 正在将 $low 变成 64 长度。因此,关于长度不足的错误。

标签: powershell bit-manipulation bitarray bitvector


【解决方案1】:

问题是我将两个BitArray 实例加在一起,导致$low 变为64 位BitArray

正确的解决方法如下。

$low = [System.Collections.BitArray]::new(@(0x93e0))
$high = [System.Collections.BitArray]::new(@(0x0004))
$high.LeftShift(16)

# Copy the "upper" 16 bits from $high to $low
16..31 | % { $low.Set($PSItem, $high[$PSItem]) }

# Convert the BitArray (singleton) to an integer array
$result = [int[]]::new(1)
$low.CopyTo($result, 0)

# Print the result
$result[0]

【讨论】:

    【解决方案2】:

    您不需要像那样遍历位数组并复制位。只需 OrXor 将数组放在一起

    $low = [System.Collections.BitArray]::new(@(0x93e0))
    $high = [System.Collections.BitArray]::new(@(0x0004))
    
    $tmp = $low.Or($high.LeftShift(16)) # Combine the 2 arrays
    
    $result = [int[]]::new(1)
    $low.CopyTo($result, 0)
    $result[0]
    

    但是,如果您的位数组总是 32 位长,那么您应该改用 BitVector32。 BitArray 备注中推荐:

    BitVector32 类是一种结构,它提供与BitArray 相同的功能,但性能更快。 BitVector32 更快,因为它是值类型,因此分配在堆栈上,而BitArray 是引用类型,因此分配在堆上。

    https://docs.microsoft.com/en-us/dotnet/api/system.collections.bitarray?view=net-5.0#remarks

    [Collections.Specialized.BitVector32]$low = 0x93e0
    [Collections.Specialized.BitVector32]$high = 0x0004
    $low.Data -bor ($high.Data -shl 16)
    

    当然你仍然可以独立访问BitVector32 中的每一位

    【讨论】:

      猜你喜欢
      • 2017-07-16
      • 2013-12-26
      • 2014-01-05
      • 1970-01-01
      • 2018-02-27
      • 2012-06-27
      • 2016-09-06
      • 2017-05-31
      • 2020-04-15
      相关资源
      最近更新 更多