仅用位运算实现加法器

shao 发表于 3年前 · 关联问题 A+B 问题

今天计算机导论学了加法器,于是参考书上的理论,仅用位运算把它实现了出来。

#include <stdbool.h> #include <stdio.h> #define put1(c, k) (c |= (1 << k)) #define put0(c, k) (c &= ~(1 << k)) #define put(c, k, b) (b ? put1(c, k) : put0(c, k)) #define get(c, k) ((c / (1 << k)) % 2) int adder(int a, int b) { bool c1 = 0; bool c2 = 0; int c = 0; int l = sizeof(a) * 8; for (int i = 0; i < l; i++) { bool b1 = get(a, i); bool b2 = get(b, i); c2 = b1 & b2; b2 = b2 ^ b1; c2 = c2 | (b2 & c1); b2 = b2 ^ c1; c1 = c2; put(c, i, b2); } return c; } int main(void) { int a, b; scanf("%d%d", &a, &b); int c = adder(a, b); printf("%d", c); return 0; }

bobby285271 发表于 3年前

#include <stdio.h> int calc(int a, int b) { return b ? calc(a ^ b, (a & b) << 1) : a; } int main() { int a, b; scanf("%d%d", &a, &b); printf("%d", calc(a, b)); }

shao 发表于 3年前

还是大佬6啊,我也想过递归的方法,不过最后用最粗暴的方式解决了。

#include <stdbool.h> #include <stdio.h> #define put1(c, k) (c |= (1 << k)) #define put0(c, k) (c &= ~(1 << k)) #define put(c, k, b) (b ? put1(c, k) : put0(c, k)) #define get(c, k) ((c / (1 << k)) % 2) int adder(int a, int b) { bool b1, b2; bool c1, c2; int c = 0; int l = sizeof(a) * 8; for (int i = 0; i < l; i++) { b1 = get(a, i); b2 = get(b, i); c2 = b1 & b2; b2 ^= b1; c2 |= (b2 & c1); b2 ^= c1; c1 = c2; put(c, i, b2); } return c; } int main(void) { int a, b; scanf("%d%d", &a, &b); int c = adder(a, b); printf("%d", c); return 0; }

shao 发表于 3年前

不使用 +-*/ 实现整数的四则运算

#include <stdio.h> int add(int a, int b) { int c; while (b) { c = a; a ^= b; b &= c; b <<= 1; } // printf("!\n"); return a; } int sub(int a, int b) { return add(a, add(~b, 1)); } int mul(int a, int b) { int t, c = 0; if (a > b) t = a, a = b, b = t; while (a) { a = sub(a, 1); c = add(c, b); } return c; } int div(int a, int b) { if (b == 0) return 0; int s = 0, c = 0; do { s = add(s, b); if (s > a) return c; c = add(c, 1); } while (c); return 0; } int mod(int a, int b) { return sub(a, mul(b, div(a, b))); } int main(void) { int a, b; scanf("%d%d", &a, &b); printf("%d", mod(a, b)); return 0; }

朕与将军解战袍 发表于 3年前

函数还可以宏定义的吗,涨知识了。 话说,大佬你的编程知识都是在哪学的,有什么资源推荐的吗?(手动狗头)

shao 发表于 3年前

我也不知道咋学的,就是自学呀,多看文章看视频查资料就会了

朕与将军解战袍 发表于 3年前

emm,好吧。

TommyBay 发表于 3年前

%%%