# Doing arithmetic with binary numbers

How do I execute binary operations in Mathematica? I want to to multiply say 1010101011 (binary) to 1111101110 (binary) and getting the result 10100111101111111010? Then I want to add the result to say 10101010000111 (binary)? Assume the all binary numbers are given as lists such as {1,0,1...}. Thanks!

-
You could zero-pad (upsample) by 2*log2(length smaller operand) or something like that, and use ListConvolve[l1,l2,,{1,-1},Modulus->2]. –  Daniel Lichtblau Mar 31 '14 at 22:26

There isn't really such a thing as binary arithmetic (at least in Mathematica). Numbers can be represented in any base, and this user-visible representation is completely independent from how arithmetic is done.

Try this:

BaseForm[(2^^1010101011)*(2^^1111101110), 2]


Things to look up:

-

You can easily convert between decimal representation and a representation in terms of binary lists with IntegerDigits and FromDigits as in the following example:

IntegerDigits[57, 2]
{1, 1, 1, 0, 0, 1}
FromDigits[%, 2]
57


It is then straight forward to write functions for arithmetic like for example:

Multiply[a_, b_] := IntegerDigits[FromDigits[a] FromDigits[b], 2];


To get a multiplication operator symbol you can use for example:

MakeExpression[RowBox[{x_, "x", y_}], StandardForm] :=
MakeExpression[RowBox[{"Multiply", "[", x, ",", y, "]"}], StandardForm]


This then make to the following evaluation possible:

{1, 0, 0} x {1, 0, 1}
{1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0}


Maybe it would be better to use another symbol than "x"...

-
I'm looking for something like {1,1,1,0,1} x {1,1,1,0,1} = {1, 0, 1, 0, 0, 1, 1, 0, 1, 1} –  Giorgio Mar 28 '14 at 16:14
I see. I edited the answer accordingly. You might also find mathematica.stackexchange.com/questions/31375/… interesting. –  cgogolin Mar 28 '14 at 16:27
Hi @Cgogolin, thanks! What I'm trying to do is to find the fastest way to multiply a binary number say b1 (with is list with one million components of zeros and ones) times b2 also a list with one million components of zeros and ones. Are you familiar with the Karatsuba Multiplication method? It claims to be much faster than conventional multiplication. The result should be a list with 2 million bits. I'll try your suggestion above and will see what happens, specially when I feed it with 2 lists of one million components each. –  Giorgio Mar 29 '14 at 0:51
I wasn't aware that the numbers were that large. I was trying to come up with a convenient method, rather than an efficient one. No, I am not familiar with Karatsuba Multiplication. –  cgogolin Mar 31 '14 at 8:10
@Giorgio If the purpose is to obtain "faster" integer multiplication, this approach is not going to get you there. –  Daniel Lichtblau Mar 31 '14 at 22:07