Re: Boolean, Binary logic
- To: mathgroup at smc.vnet.net
- Subject: [mg9804] Re: Boolean, Binary logic
- From: Daniel Lichtblau <danl>
- Date: Fri, 28 Nov 1997 05:35:16 -0500
- Organization: Wolfram Research, Inc.
- Sender: owner-wri-mathgroup at wolfram.com
seanross at worldnet.att.net wrote: > > I have a need for And OR XOR Not functions that operate on binary > numbers, ie digital logic. For example And[2^^10,2^^10]=2^^11, > Not[2^^100]=2^^011 etc. I was really surprised that mathematicas' > logical functions only operated on boolean expressions. Did I miss > something? Is there a package out there I didn't see? Thanks for your > help. > -- > Remove the _nospam_ in the return address to respond. I assume you want And[2^^10,2^^10] --> 2^^10 (that is, 2), not 2^^11. Our next release will provide this capability via BitAnd, BitOr, BitXor, and some related routines. Here are some examples. In[18]:= a1 = 1234314324; a2 = 4341243243; In[19]:= BitAnd[a1,a2] Out[19]= 8520768 In[20]:= BitOr[a1,a2] Out[20]= 5567036799 In[21]:= BitXor[a1,a2] Out[21]= 5558516031 How to get this functionality today? In available versions of Mathematica this can be simulated without undue stress. I have code to do just this below (I wrote it to test the new bit-operations after implementing them). It is much slower but still should be adequate for working with inputs of moderate size. testbitop[opcode[aox_], a_, b_, c__] := (* make it associative *) testbitop[opcode[aox], testbitop[opcode[aox], a, b], c] testbitop[opcode[aox_], a_Integer, b_Integer] /; (* basic 1-bit case *) (a==0||a==1) && (b==0||b==1) := Switch[aox, and, a*b, or, a+b-a*b, xor, Mod[a+b,2]] testbitop[opcode[aox_], a_List, b_List] := Module[ (* lists of bits *) {a1, b1, lena=Length[a], lenb=Length[b], len}, len = Max[lena,lenb]; a1 = If [lena<len, Join[Table[0, {len-lena}],a], a]; b1 = If [lenb<len, Join[Table[0, {len-lenb}],b], b]; Inner[testbitop[opcode[aox],#1,#2]&, a1, b1, List] ] testbitop[opcode[aox_], a_Integer, b_Integer] := FromDigits[ (* noneg ints *) testbitop[opcode[aox], IntegerDigits[a,2], IntegerDigits[b,2]], 2] In[26]:= testbitop[opcode[and], a1,a2] Out[26]= 8520768 In[27]:= testbitop[opcode[or], a1,a2] Out[27]= 5567036799 In[28]:= testbitop[opcode[xor], a1, a2] Out[28]= 5558516031 Daniel Lichtblau Wolfram Research