Recently I decided I needed some binary operators in OpenSCAD. As there are no built-in binary operators, and a quick search didn’t reveal any handy libraries, I decided to write some.

The solution is not very elegant, but seems to work.

The binary boxes example and bitSet function I found over at Boolean Operators in OpenScad – Counting in Binary

```
//******************************************************************************
// Description: Binary operators
//
//
// Copyright CC-BY-SA Donotdespisethesnake 2020
// with help from Andre
//
// Revision History:
//
// 1 2020-10-15 Initial version
//******************************************************************************
/* [Hidden] */
/* Not very elegant, but ... */
and_table = [0,0,0,1];
or_table = [0,1,1,1];
xor_table = [0,1,1,0];
// From Andre
function bitSet(num, bit) = floor(num / pow(2, bit)) % 2;
// AND
function bitAndN(x,y,n) = (n==0) ?
and_table[(bitSet (x,n) ? 1 : 0) + (bitSet(y,n) ? 2 : 0)] * pow(2,n) :
and_table[(bitSet (x,n) ? 1 : 0) + (bitSet(y,n) ? 2 : 0)] * pow(2,n) + bitAndN(x,y,n-1);
function bitAnd (x,y) = bitAndN (x,y,31);
// OR
function bitOrN(x,y,n) = (n==0) ?
or_table[(bitSet (x,n) ? 1 : 0) + (bitSet(y,n) ? 2 : 0)] * pow(2,n) :
or_table[(bitSet (x,n) ? 1 : 0) + (bitSet(y,n) ? 2 : 0)] * pow(2,n) + bitOrN(x,y,n-1);
function bitOr (x,y) = bitOrN (x,y,31);
// XOR
function bitXorN(x,y,n) = (n==0) ?
xor_table[(bitSet (x,n) ? 1 : 0) + (bitSet(y,n) ? 2 : 0)] * pow(2,n) :
xor_table[(bitSet (x,n) ? 1 : 0) + (bitSet(y,n) ? 2 : 0)] * pow(2,n) + bitXorN(x,y,n-1);
function bitXor (x,y) = bitXorN (x,y,31);
//******************************************************************************
// demo
//******************************************************************************
/* [Parameters] */
num_bits = 8; // [1:32]
a=10;
b=12;
unit_size = 20;
// draw a row of bits
module row (a)
{
for (j=[0:num_bits-1])
{
n = num_bits-1-j;
translate ([(unit_size+1)*j,0,0])
difference ()
{
cube ([unit_size,unit_size,unit_size], center=true);
if (!bitSet (a, n))
translate ([0,0,2])
cube ([unit_size-2,unit_size-2,unit_size-2], center=true);
}
}
}
// label the bits
for (j=[0:num_bits-1])
{
n = num_bits-1-j;
translate ([ n*(unit_size+1),15,0])
rotate ([0,0,90])
text (str("2^", j, "= ", pow(2,j)), halign="left", valign="center");
}
// Operand A
translate ([-20,-5,0])
text (str(a,"="), halign="right");
row (a);
// Operand B
translate ([0,-(unit_size+1),0])
{
translate ([-20,-5,0])
text (str(b,"="), halign="right");
row (b);
}
// AND function
translate ([0,-(unit_size+1)*3,0])
{
translate ([-20,-5,0])
text (str(a," AND ", b, " ="), halign="right");
row (bitAnd (a, b));
}
// OR function
translate ([0,-(unit_size+1)*4,0])
{
translate ([-20,-5,0])
text (str(a," OR ", b, " ="), halign="right");
row (bitOr (a, b));
}
// XOR function
translate ([0,-(unit_size+1)*5,0])
{
translate ([-20,-5,0])
text (str(a," XOR ", b, " ="), halign="right");
row (bitXor (a, b));
}
```