LoginSignup
1
1

More than 3 years have passed since last update.

ビット演算とシフトによる加算関数

Last updated at Posted at 2019-10-06

ビット演算とシフトのみによる加算ルーチンです。
2進数加算結果は、A⊕B⊕carryになります。
加算のキャリーは、(A&B)|(A&carry)|(B&carry)になります。
正確に知りたい方はベン図と真理表を書いて求めて下さい。
対称性があるので、ベン図はきれいな三つ葉模様になります。
int addbit()が本体です。
C言語で書かれています。

addbit.c
int addbit(int a,int b) {
    int cy=0,t=1,s=0;
    while(t) {
        s|=(a&t)^(b&t)^cy;
        cy=(t&(a&b|cy&b|cy&a))<<1;
        t<<=1;
    }
    return(s);
}
1
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1