View Single Post
  #4   Report Post  
Posted to microsoft.public.excel.programming
Ron Rosenfeld Ron Rosenfeld is offline
external usenet poster
 
Posts: 5,651
Default How can I do AND operation on two binary numbers in MS Excel?

On Wed, 11 Jan 2006 14:50:02 -0800, "Zuke"
wrote:

I want to do AND say to the following:
00101001
AND to
10001001

and should get the following answer:

00001001

What function should I use in MS Excel to get this?



I don't know how to do it with a worksheet function. But you can write a UDF
(user-defined function) in VBA to do that.

<alt-F11 opens the VB Editor.

Ensure your project is highlighted in the Project Explorer window. Then
Insert/Module and paste the code below into the window that opens.

You can use the function by typing:

=BinaryAND(00101001,00001001)

or by placing those numbers into cells, and using the cell references.

The AND function in VBA is supposed to do something similar, but I cannot seem
to get it to work properly at this time.

================================
Option Explicit
Function BinaryAND(n1, n2) As String
Dim i As Long
Dim l As Long
Dim b1 As String, b2 As String
Dim Fmt As String
Dim temp As String

l = Application.WorksheetFunction.Max(Len(n1), Len(n2))

Fmt = Application.WorksheetFunction.Rept("0", l)

b1 = Format(n1, Fmt)
b2 = Format(n2, Fmt)

For i = 1 To l
temp = temp & Mid(b1, i, 1) * Mid(b2, i, 1)
Next i

BinaryAND = temp

End Function
===================================


--ron