首页 > 解决方案 > 从真值表构建数字乘数的通用规则

问题描述

我有一些真值表,主要是 AND,基于我用于数学运算的 0、1、-1:

示例 1:

var a,b,c;
if(a ==  1 && b == 1) c = 0;
if(a ==  1 && b == 0) c = 0;
if(a == -1 && b == 1) c = 0;
if(a == -1 && b == 0) c = 1;

示例 2:

var a,b,c;
if(a ===  1 && b === 1) c =  1;
if(a ===  1 && b === 0) c =  1;
if(a === -1 && b === 1) c =  1;
if(a === -1 && b === 0) c = -1;

例如,第一个可以表示如下:

c = (a>>1)*(b-1);

我还想只使用数学或位运算符转换第二个真值表,怎么做?

是否有任何通用规则可以轻松创建这种单行表达式?

标签: javascriptbit-manipulation

解决方案


You can use a generic superoptimizer such as this one I wrote (unfortunately not very user friendly): https://github.com/falk-hueffner/sematrope

This will give you (a + b) >>> 31 for your first example and ((a + b) | b) & a for the second.

For a more systematic approach, you can convert -1/1 to 0/1 by (x >> 1) + 1, do regular logic operations with |&^, and then (if needed) convert 0/1 to -1/1 by x ^ (x - 1).


推荐阅读