好的,我有两个单元格,其中包含一串位 0111010 和 0101011。我想将两者异或,以便生成的单元格为 0010001。
我知道您可以将其用于布尔值
=OR(AND(A1,NOT(A2)),AND(A2,NOT(A1)))
但它不适用于一串位。
您需要使用 VBA 来执行此操作。如果你打开VBA,新建一个Module,进入函数
Public Function BITXOR(x As Long, y As Long)
BITXOR = x Xor y
End Function
然后,您可以使用 DEC2BIN 和 BIN2DEC 将二进制转换为十进制以运行此函数。例如:
单元格 A1 = 0111010
单元格 A2 = 0101011
=DEC2BIN(BITXOR(BIN2DEC(A1),BIN2DEC(A2)))
您可以使用 VBA 执行此操作:
Public Function XOR_binary(b1, b2) As String
Dim len_b1
Dim len_b2
Dim len_diff
Dim i
Dim bit1
Dim bit2
' see if the two string are the same length. If not, add 0's to
' the beginning of the shorter string
len_b1 = Len(b1)
len_b2 = Len(b2)
len_diff = len_b1 - len_b2
Select Case len_diff
Case Is < 0
' b2 is longer
b1 = String(Abs(len_diff), "0") & b1
Case Is = 0
' they're the same length
Case Is > 0
' b1 is longer
b2 = String(len_diff, "0") & b2
End Select
XOR_binary = ""
For i = Len(b2) To 1 Step -1
bit1 = CInt(Mid(b1, i, 1))
bit2 = CInt(Mid(b2, i, 1))
XOR_binary = CInt(bit1 Xor bit2) & XOR_binary
Next i
End Function
可能不是最好的实现,但它确实有效。
使用您的示例,A3
包含:
=XOR_Binary(A1,A2)
生成的字符串将具有与您传入的最长字符串相同的位数。
这是一个不使用 VBA的解决方案:
=TEXT(SUMPRODUCT(MOD(INT(MID(A1,{1,2,3,4,5,6,7},1))+INT(MID(A2,{1,2,3,4,5,6,7},1)),2),{1000000,100000,10000,1000,100,10,1}),"0000000")
XOR
这使用SUMPRODUCT
and计算按位TEXT
,将其转换为一串位。
注意:此公式要求两个输入值的长度都为 7(根据您自己的示例),输出的长度也为 7。为了允许不同的输入长度,只需实现必要的截断和/或填充。
您可以选择使用一些速记定义:
BitPositions
为={1,2,3,4,5,6,7}
(7位),BitStrings
为={1000000,100000,10000,1000,100,10,1}
(7位),BitFormat
为="0000000"
(7位),那么你的公式可以变得更清晰/更短/更清晰:
=TEXT(SUMPRODUCT(MOD(INT(MID(A1,BitPositions,1))+INT(MID(A2,BitPositions,1)),2),BitStrings),BitFormat)
这也使得处理更大的位串变得更容易,例如:
BitPositions
为=ROW(INDIRECT("1:32"))
(32 位),BitStrings
为=10^(32-ROW(INDIRECT("1:32")))
(32 位),BitFormat
为=REPT("0",32)
(32 位)如果您希望实施NOT
/ OR
/ AND
/等。那么你可以从这些小数对应的公式中获得灵感;尽管它也使用十进制输入,但这里有一些更深入的解释。XOR
SUMPRODUCT
每个位 =1-(A1<>0)+(A2<>0)。
您可以使用以下公式将其拆分为上述公式的单独列: =MID(A1|7|1) =MID(A1|6|1) =MID(A1|5|1) =MID(A1|4|1) =MID(A1|3|1) =MID(A1|2|1) =MID(A1|1|1) ...
' 这个 VBA 返回一个必须在工作表上格式化的双精度。
Option Explicit
Public Function MYXOR(r1 As Range, r2 As Range) As Double
'r1 and r2 are expected as HEX; for example,
'DEC2HEX(CODE("B")) returns ASCII of "B" as HEX
On Error GoTo ErrHandler
MYXOR = "&H" & r1.Value Xor "&H" & r2.Value
GoTo CleanUp
ErrHandler:
MYXOR = Err.Number
Resume CleanUp
CleanUp:
' format the double being returned in MYXOR with TEXT(DEC2HEX(MYXOR(C9,F9)),"00000")
' number of leading zeroes according to the size of the HEX in r1 and r2
End Function