tags:

views:

3001

answers:

3

Okay I have two cells with a string of bits 0111010 and 0101011. I want to XOR the two together so that the resulting cell would be 0010001.

I know you can use this for boolean values

=OR(AND(A1,NOT(A2)),AND(A2,NOT(A1)))

but it doesn't work for a string of bits.

A: 

=1-(A1<>0)+(A2<>0) for each bit.

You can split it into individual columns for the above formula using this: =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) ...

Chris Ballance
How do you do the for each bit part though?
James Van Boxtel
+6  A: 

You need to use VBA to do this. If you open VBA, create a new Module and enter the function

Public Function BITXOR(x As Long, y As Long)
    BITXOR = x Xor y
End Function

You can then use the DEC2BIN and BIN2DEC to convert from binary to decimal to run this function. For example:

Cell A1 = 0111010

Cell A2 = 0101011

=DEC2BIN(BITXOR(BIN2DEC(A1),BIN2DEC(A2)))
Robin Day
Thanks!For other users, to use DEC2BIN go to Tools -> Addins -> Analysis toolpak.To do VBA go to Tools -> Macros -> Visual Basic Editor
James Van Boxtel
+1  A: 

You can do this with 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

Probably not the best implementation, but it works.

Using your example, A3 contains:

=XOR_Binary(A1,A2)

The resulting string will have the same number of bits as the longest string you pass in.

Patrick Cuff