汉明距离与 powershell 的比较

BX13

我如何将 8 位与另一个 8 位进行比较以获得如下内容:

first Nr     1 0 0 0 1 1 0 1
second Nr    1 0 1 0 1 0 0 0
Result       r r f r r f r f

r = right 
f = false

谢谢

克莱门特0

带注释的解决方案:

$firstNrBin  = '1 0 0 0 1 1 0 1'
$secondNrBin = '1 0 1 0 1 0 0 0'

# Convert the binary number strings to [byte]s (unsigned 8-bit values).
$firstNr = [Convert]::ToByte($firstNrBin -replace ' ', 2)   # 141 == 0x8d
$secondNr = [Convert]::ToByte($secondNrBin -replace ' ', 2) # 168 == 0xa8

# Perform bitwise XOR logic and negate the result to get a bit field
# that reflects the bits where the input numbers match.
# Note the need use of -band 0xff to limit the result to 8 bits - see
# explanation below.
# -> 218 == 0xda = 11011010
$bitsInCommon = [byte] (-bnot ($firstNr -bxor $secondNr) -band 0xff)

# Convert the bit field back into a binary representation, 0-padded to 8 chars.
# -> '11011010'
$bitsInComminBin = [Convert]::ToString($bitsInCommon, 2).PadLeft(8, '0')

# Produce the desired output format with string manipulation
$result = ([char[]] $bitsInComminBin -replace '1', 'r' -replace '0', 'f') -join ' '

# Output the result
[ordered] @{
  'first Nr' = $firstNrBin
  'second Nr' = $secondNrBin
  'Result' = $result
}

以上产生:

Name                           Value
----                           -----
first Nr                       1 0 0 0 1 1 0 1
second Nr                      1 0 1 0 1 0 0 0
Result                         r r f r r f r f

请注意,PowerShell 的按位运算符输出[int]-System.Int32作为最小的数据类型,即有符号数字

因此,您必须使用-band运算符显式屏蔽掉额外的位,因为直接转换回无符号类型是行不通的。

在手头的情况下:

$firstNr -bxor $secondNr # 141 -bxor 168

产生37一个[int]值,即以下 32 位:

00000000000000000000000000100101

应用于-bnot[int]产生按位补码:

11111111111111111111111111011010

作为[int],这是一个负数,因为设置了高位:-38

您不能将其直接转换回无符号类型,例如[byte]仅获得最低 8 位,但您可以使用-band位掩码0xff将前 8 位以外的所有位归零 - 但请注意,此时结果仍然是[int]

-bnot -38 -band 0xff

产生以下位:

00000000000000000000000000100101

作为一个[int],这是37,您可以安全地转换回[byte]

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章