javascript - 从真值表构建数字乘数的通用规则
问题描述
我有一些真值表,主要是 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);
我还想只使用数学或位运算符转换第二个真值表,怎么做?
是否有任何通用规则可以轻松创建这种单行表达式?
解决方案
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)
.
推荐阅读
- c++ - 使用 CRTP 将基类的子类传递给构造函数?
- python-3.x - 检查日期列中是否缺少月份数据
- typescript - 如果函数将超类作为其返回类型,TypeScript 可以返回子类吗?
- selenium - Docker 和 Selenium 网格错误。转发新会话时出错 空池
- reactjs - 使用 React Router 切换到不同组件时出现随机内存泄漏错误
- excel - 数组公式中的 IFERROR="" 未输入空白
- python - 从 ascii 表中选择 5 个随机数据元素
- java - 根据特定输入动态生成字符串的代码
- c++ - 如何解析列存储格式的 XML 文件?
- python - 在 pythonanywhere.com 上使用 PyRFC 连接到 SAP